package com.opd.soeghtool;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.graphics.Point;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.media.AudioManager;
import android.media.MediaRouter;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.support.v4.app.FragmentActivity;
import android.support.v4.content.FileProvider;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AlertDialog;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.DigitsKeyListener;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.SimpleAdapter;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import com.nostra13.universalimageloader.BuildConfig;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;


public class MainActivity extends FragmentActivity implements View.OnClickListener {


    private final String TAG = "SOEMain";
    private final String LOCAL_PATH = "/SOEGHTool";
    private final String NAME_UPDATE_APK = "/update.apk";
    private final String VER_URL_PUSH ="http://www.opd-display.com/app/data/appVersion.json";
    private final String VER_URL ="http://www.opd-display.com/app/data/appVersion_manual.json";
    //private final String VER_URL ="http://www.opd-display.com/app/test/appVersion.json";
    //private final String APK_URL ="http://www.opd-display.com/app/data/download/SOETool_V1.1.0.3_20190618.apk";
    private static final String ACTION_USB_PERMISSION = "com.opd.soeghtool.USB_PERMISSION";
    GlobalVar mGlobalVar;
    private ViewPager mViewPager;
    private PagerAdapter mAdapter;
    private List<View> mViews = new ArrayList<View>();
    App_Info app_info;

    private LinearLayout mGameList,layout_app_setting;
    private LinearLayout mGamePadSetting;

    private ProgressDialog mProgressDialog;

    private RelativeLayout layout_gp_setting_image_size,layout_gp_setting_new_phone,layout_gp_setting_new_update,layout_gp_setting_new_game,layout_gp_setting_new_rocker,layout_gp_setting_new_reset,layout_gp_setting_new_data,layout_gp_setting_new_inject,layout_gp_setting_new_button;

    private RelativeLayout layout_app_setting_exit,layout_app_setting_lang,layout_app_setting_version,layout_app_setting_customer,layout_app_setting_about,layout_app_setting_product,rl_main_top_layout,layout_app_setting_status,layout_app_setting_new_inject,layout_app_setting_new_update,layout_app_setting_new_reset,layout_app_setting_image_size;

    View connect_mode_view,device_update_layout;
    ImageView iv_connect_mode_cnt_sta;
    TextView tv_connect_mode_cnt_sta,tv_device_update_version_cur;

    View app_status_info;
    TextView tv_app_status_info_device_name_content,tv_app_status_info_device_ver_content,tv_app_status_info_device_connect_content,tv_app_status_info_device_type_content,tv_app_status_info_device_mode_content;
    RelativeLayout app_status_info_device_mode_layout;
    RadioButton rb_connect_mode_normal,rb_connect_mode_inject,rb_connect_mode_gp_normal,rb_connect_mode_gp_touch,rb_connect_mode_gp_pc;
    RadioGroup rbg_connect_mode_gp_mode;
    //TextView tv_setting_new_phone_cur,tv_setting_new_game_cur;

    private ImageView iv_bottom_game,iv_bottom_gp_setting,iv_bottom_app_setting;
    private ImageView iv_top_connect,iv_launch_view;
    // USB Transfer
    private final int INTERFACE_CLASS = 0x03;//30264;
    private final int INTERFACE_SUBCLASS = 0x00;//30264;
    private final int INTERFACE_PROTOCOL = 0x00;//30264;
    private final int USBCMD_TIMEOUT = 20000;
    private final int USBCMD_TIMEOUT_LONG	 = 100000;
    byte[] g_u8CodeBuf,g_u8DataBuf;
    int g_lCodeLen=0,g_lDataLen;

    private boolean bInjectFirstTime,bInjectVerifyFail,bIsConnectedBefore=false,bIsReMindToUpdate=false,bIsCheckSumDiff=false;
    int mInjectTimeCounter = 0,mInjectVerifyStep=0;
    // Page Launch
    RelativeLayout launchLayout;
    GameListPopupWindow gameListPopupWindow;
    Button btn_launch_exit;
    TextView tv_bottom_game,tv_bottom_gp_setting,tv_bottom_app_setting;
    // Page status
    TextView tv_top_title,tv_main_debug_warning;
    // Page gamelist
    MyGridView lv_gamelist;
    MyAdapter myAdapter;
    ArrayList<Map<String, Object>> dataList,gameList;

    BluetoothUtils bluetoothUtils;
    // Page gpSetting

    boolean bIsCheckedGpVersion = false;
    boolean bIsGetPtTbl = false;
    int ptTbl[];
    int mRes_Wid,mRes_Hei;
    // update
    ProgressDialog pDialog;
    boolean	m_bProgram_APROM;
    boolean	m_bProgram_NVM;
    boolean	m_bProgram_Config;
    boolean	m_bErase;
    boolean    g_bIsRegisterUsbPermitRec=false;
    boolean bIsAlreadyReadIntroduce;
    boolean bIsGPNormalMode;
    boolean bIsSendMouseSwitchToDevice = false;
    int m_progress = 0;
    int m_eProcSts = 0;
    long m_CONFIG[];
    long m_CONFIG_User[];
    long m_ulDeviceID;
    int m_uAPROM_Addr;
    int m_uAPROM_Size;
    int m_uNVM_Addr;
    int m_uNVM_Size;

    private int mEnterDebugCounter = 0;
    //BroadcastReceiver myBroadcastReceiver;
    // Page Setting
    boolean bIsAppCanUpdate = false,bIs1stGetOverFloatPermit = true;
    private final int LAUNCHSCREEN = 0x12;
    private final int LAUNCHDEBUG = 0x13;
    private final int PermitRequest = 0x14;
    private final int USBPermitRequest = 0x15;
    private final int VERSION_CHECK_NOUPDATE = 0x16;
    private final int VERSION_CHECK_UPDATE = 0x17;
    private final int TO_GET_SERVER_STATUS = 0x18;
    private final int UPDATE_SERVER_STATUS = 0x19;
    private final int INJECT_VERIFY_STATUS = 0x1A;
    private final int CHECK_GP_VERSION = 0x1B;
    private final int TO_CNT_BLE_DEVICE = 0x1C;

    private final int LAUNCHSHOWTIME = 3000;

    Handler handler;
    //boolean aaa = true;
    UdpSocketHelper udpSocketHelper;

    @SuppressLint("SourceLockedOrientationActivity")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        //requestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);
        if(Transfer_Con.ENABLE_LANGUAGE_SWITCH) {
            Resources resources = getResources();
            Configuration config = resources.getConfiguration();
            DisplayMetrics dm = resources.getDisplayMetrics();
            String language = config.locale.getLanguage();
            if (language.contains("en")) {
                config.locale = Locale.ENGLISH;
                resources.updateConfiguration(config, dm);
            } else if (language.contains("cn")) {
                config.locale = Locale.CHINA;
                resources.updateConfiguration(config, dm);
            }
            else if (language.contains("ja")) {
                config.locale = Locale.JAPAN;
                resources.updateConfiguration(config, dm);
            } else {
                config.locale = Locale.getDefault();
                resources.updateConfiguration(config, dm);
            }
        }
        setContentView(R.layout.activity_main);
        launchLayout = (RelativeLayout) findViewById(R.id.lv_launch_screen);
        mGlobalVar = (GlobalVar)getApplication();
       //getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
        //        WindowManager.LayoutParams.FLAG_FULLSCREEN);



        if(false) {
            MediaRouter router=null;

            WindowManager windowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
                router=(MediaRouter)getSystemService(MEDIA_ROUTER_SERVICE);
            String strMsg="";
            if(router!=null)
            {
                strMsg = router.getDefaultRoute().toString();
            }
            else if(router.getDefaultRoute().getPresentationDisplay()!=null)
            {
                strMsg=router.getDefaultRoute().getPresentationDisplay().getName();
                DisplayMetrics dm1=new DisplayMetrics();
                Point  point =new Point();
                router.getDefaultRoute().getPresentationDisplay().getRealMetrics(dm1);
                router.getDefaultRoute().getPresentationDisplay().getSize(point);
                //strMsg = router.getDefaultRoute().getPresentationDisplay().toString();
               // strMsg += String.format("height=%d,width=%d,",router.getDefaultRoute().getPresentationDisplay().getHeight(),router.getDefaultRoute().getPresentationDisplay().getWidth());
                //strMsg += String.format("height=%d,width=%d,",dm1.heightPixels,dm1.widthPixels);
                //strMsg += String.format("height=%d,width=%d,",point.x,point.y);
            }
            else
            {
                strMsg = "null";
            }
            //Toast.makeText(this,windowManager.getDefaultDisplay().toString(),Toast.LENGTH_LONG).show();
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setMessage(strMsg)
                    .create().show();

        }
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        getWindow().getDecorView().addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
            @Override
            public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
                initStatusBar();
                getWindow().getDecorView().removeOnLayoutChangeListener(this);
            }
        });
        mGlobalVar.myUsbManager = (UsbManager) getSystemService(USB_SERVICE);
        handler = new Handler();
        loadUserData();

        bluetoothUtils = new BluetoothUtils(this);

        /*
        if(Transfer_Con.ENABLE_LANGUAGE_SWITCH) {
            if (mGlobalVar.getCurLanguageIndex() == 0) {
                config.locale = Locale.getDefault();
                resources.updateConfiguration(config, dm);
            } else if (mGlobalVar.getCurLanguageIndex() == 1)    // En
            {
                config.locale = Locale.ENGLISH;
                resources.updateConfiguration(config, dm);
            } else if (mGlobalVar.getCurLanguageIndex() == 2)    // En
            {
                config.locale = Locale.CHINA;
                resources.updateConfiguration(config, dm);
            }
        }
         */
        ptTbl = new int[mGlobalVar.getDeviceMaxButton()*2];
        btn_launch_exit=(Button)findViewById(R.id.btn_launch_exit);
        btn_launch_exit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        iv_launch_view = (ImageView)findViewById(R.id.iv_launch_view);
        tv_top_title = (TextView)findViewById(R.id.tv_top_title);
        tv_main_debug_warning = (TextView)findViewById(R.id.tv_main_debug_warning);
        rl_main_top_layout = findViewById(R.id.rl_main_top_layout);
        IntentFilter usbDeviceStateFilter = new IntentFilter();
        usbDeviceStateFilter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
        usbDeviceStateFilter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
        registerReceiver(myBroadcastReceiver,usbDeviceStateFilter);
        udpSocketHelper = new UdpSocketHelper(4000,4400);
        bIsGPNormalMode = false;
        // Notch
        if(mGlobalVar.hasNotchScreen(MainActivity.this))
        {
            mGlobalVar.setIsNotchFlag(true);
        }

        if(BuildConfig.DEBUG)
        {
            tv_main_debug_warning.setVisibility(View.VISIBLE);
        }

        rl_main_top_layout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                launchHandler.removeMessages(LAUNCHDEBUG);
                mEnterDebugCounter++;
                if(mEnterDebugCounter>5)
                {
                    mEnterDebugCounter = 0;
                    final EditText inputEdit = new EditText(MainActivity.this);
                    AlertDialog.Builder builder= new AlertDialog.Builder(MainActivity.this);
                    builder.setTitle("请输入验证码")
                           .setView(inputEdit)
                            .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    String str = String.valueOf(inputEdit.getText());
                                    Log.d(TAG,str);
                                    if(str.equals("1011755")) {
                                        Intent intent = new Intent();
                                        intent.setClass(MainActivity.this, DebugActivity.class);
                                        startActivity(intent);
                                    }
                                    else if(str.equals("opd1755"))
                                    {
                                        Intent intent = new Intent();
                                        intent.setClass(MainActivity.this, AdvDebugActivity.class);
                                        startActivity(intent);
                                    }
                                    else if(str.equals("soe1755"))
                                    {
                                        Intent intent = new Intent();
                                        intent.setClass(MainActivity.this, USBDebugActivity.class);
                                        startActivity(intent);
                                    }
                                }
                            })
                            .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {

                                }
                            })
                            .setCancelable(false)
                            .create().show();
                }
                Message msg = new Message();
                msg.what = LAUNCHDEBUG;
                launchHandler.sendMessageDelayed(msg, 1000);//设置在SPLASHTIME时间后，发送消息
            }
        });
        //mGlobalVar.setIsPortraitGame(true);
        //


        InitView();
        InitEvent();

        if(mGlobalVar.getIsWaitForUPdate()&&mGlobalVar.getbIsUsbConnect()&&(!mGlobalVar.getbIsTransferMode())) {

            SharedPreferences.Editor editor1 = getSharedPreferences(Transfer_Con.SAVENAME, MODE_PRIVATE).edit();
            editor1.putBoolean("waitUpdate", false);
            editor1.commit();
            UpdateFw();
        }

        Message msg = new Message();
        msg.what = LAUNCHSCREEN;//PermitRequest;
        launchHandler.sendMessageDelayed(msg, LAUNCHSHOWTIME);//设置在SPLASHTIME时间后，发送消息
        checkServerVersionCode();
        //launchLayout.setVisibility(View.GONE);
        if(!mGlobalVar.getIsSocketRecvServiceRunning()) {
        Intent intent = new Intent(MainActivity.this, SocketRecvService.class);
        startService(intent);
        }

        mProgressDialog = new ProgressDialog(this);

        mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);//转盘

        mProgressDialog.setCancelable(false);
        mProgressDialog.setMessage(getResources().getString(R.string.string_pop_connecting_wait));
        mProgressDialog.setCanceledOnTouchOutside(false);
    }
    private Handler launchHandler = new Handler(){
        public void handleMessage(Message msg){
            super.handleMessage(msg);
            switch (msg.what){
                case LAUNCHSCREEN:
                    launchLayout.setVisibility(View.GONE);
                    autoPermitRequest();
                    break;
                case LAUNCHDEBUG:
                    mEnterDebugCounter = 0;
                    break;
                case PermitRequest:
                    autoPermitRequest();
                    break;
                case CHECK_GP_VERSION:

                    break;

                case TO_GET_SERVER_STATUS:
                    getSimulateStatus();
                    try {
                        Thread.sleep(200);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    getInjectStatus();
                    mProgressDialog.create();
                    mProgressDialog.show();
                    break;
                case UPDATE_SERVER_STATUS:
                    mProgressDialog.dismiss();
                    if(!mGlobalVar.getbIsUsbConnect())
                    {
                        rb_connect_mode_inject.setEnabled(false);
                        rb_connect_mode_normal.setEnabled(false);
                        rb_connect_mode_gp_normal.setEnabled(false);
                        rb_connect_mode_gp_touch.setEnabled(false);
                        rb_connect_mode_gp_pc.setEnabled(false);

                        tv_app_status_info_device_name_content.setText(getResources().getString(R.string.string_app_status_info_content_unknown));
                        tv_app_status_info_device_ver_content.setText(getResources().getString(R.string.string_app_status_info_content_unknown));
                        tv_app_status_info_device_connect_content.setText(getResources().getString(R.string.string_pop_connect_disconnect));
                        tv_app_status_info_device_type_content.setText(getResources().getString(R.string.string_app_status_info_content_unknown));
                        tv_app_status_info_device_mode_content.setText(getResources().getString(R.string.string_app_status_info_content_unknown));
                        iv_connect_mode_cnt_sta.setImageResource(R.drawable.disconnect);
                    }
                    else
                    {
                        if(mGlobalVar.getIsInjectServerRunning())
                        {
                            rb_connect_mode_gp_normal.setEnabled(true);
                            rb_connect_mode_gp_touch.setEnabled(true);

                            if(mGlobalVar.getIsSimulateMode())
                            {
                                if(mGlobalVar.getIsPC360Mode())
                                    rb_connect_mode_gp_pc.setChecked(true);
                                else
                                    rb_connect_mode_gp_normal.setChecked(true);
                            }
                            else
                            {
                                rb_connect_mode_inject.setEnabled(true);
                                rb_connect_mode_normal.setEnabled(true);
                                rb_connect_mode_gp_touch.setChecked(true);
                                if (mGlobalVar.getIsInjectData()) {
                                    rb_connect_mode_inject.setChecked(true);
                                    rb_connect_mode_normal.setEnabled(false);
                                    //Toast.makeText(MainActivity.this, getResources().getString(R.string.string_pop_connecting_wait), Toast.LENGTH_SHORT).show();
                                    mGlobalVar.setIsInjectMode(true);
                                    if (bInjectFirstTime || bInjectVerifyFail) {
                                        showInjectVerify();
                                    }
                                } else {
                                    rb_connect_mode_inject.setChecked(false);
                                    rb_connect_mode_normal.setChecked(true);
                                }
                            }
                        }
                        else
                        {
                            rb_connect_mode_gp_normal.setEnabled(true);
                            rb_connect_mode_gp_touch.setEnabled(true);
                            rb_connect_mode_inject.setEnabled(false);
                            rb_connect_mode_normal.setEnabled(false);
                            if(mGlobalVar.getIsSimulateMode())
                            {
                                if(mGlobalVar.getIsPC360Mode())
                                    rb_connect_mode_gp_pc.setChecked(true);
                                else
                                    rb_connect_mode_gp_normal.setChecked(true);
                            }
                            else
                            {
                                rb_connect_mode_gp_touch.setChecked(true);
                            }
                        }
                        tv_app_status_info_device_name_content.setText(mGlobalVar.getDeviceName());
                        tv_app_status_info_device_ver_content.setText(mGlobalVar.getStrFwVer());
                        tv_app_status_info_device_connect_content.setText(getResources().getString(R.string.string_pop_connect_already_connect));
                        if(mGlobalVar.getIsSimulateMode())
                        {
                            if(mGlobalVar.getIsPC360Mode())
                                tv_app_status_info_device_type_content.setText(getResources().getString(R.string.string_connect_mode_gp_pc360));
                            else
                                tv_app_status_info_device_type_content.setText(getResources().getString(R.string.string_connect_mode_gp_normal));
                        }
                        else
                        {
                            tv_app_status_info_device_type_content.setText(getResources().getString(R.string.string_connect_mode_gp_touch));
                        }

                        if(mGlobalVar.getIsInjectMode())
                            tv_app_status_info_device_mode_content.setText(getResources().getString(R.string.string_connect_mode_inject));
                        else
                            tv_app_status_info_device_mode_content.setText(getResources().getString(R.string.string_connect_mode_normal));

                        iv_connect_mode_cnt_sta.setImageResource(R.drawable.connect);

                    }
                    //if(!bIsCheckedGpVersion)
                    {
                        bIsCheckedGpVersion = true;
                        if(Transfer_Con.ENABLE_S2_QUICK_MENU) {
                            if(mGlobalVar.getDeviceIndex()==Transfer_Con.DEVICE_HN1_INDEX) {
                                if (mGlobalVar.get_IntVersion() >= mGlobalVar.SUPPORT_MENU_KEY_VER) {
                                    mGlobalVar.setIsSupportMenuKey(true);
                                } else {
                                    mGlobalVar.setIsSupportMenuKey(false);
                                }

                                if (mGlobalVar.get_IntVersion() >= mGlobalVar.SUPPORT_MENU_KEY_VER+2) {
                                    mGlobalVar.setIsSupportMenuKeyOnOff(true);
                                } else {
                                    mGlobalVar.setIsSupportMenuKeyOnOff(false);
                                }

                                if(Transfer_Con.ENABLE_S2_MENU_COVER)
                                {
                                    if (mGlobalVar.get_IntVersion() == (mGlobalVar.SUPPORT_MENU_KEY_VER+1))
                                        mGlobalVar.setIsForceS2Enable(true);
                                    else
                                        mGlobalVar.setIsForceS2Enable(false);
                                }
                                if(mRes_Hei>mRes_Wid) {
                                    int retry = 5;
                                    while(retry>0) {
                                        if(mGlobalVar.tranSet_Value(Transfer_Con.HID_CMD_SET_SCREEN_RESOLUTION, mRes_Hei, mRes_Wid))
                                            break;
                                        retry--;
                                    }
                                }
                                else {
                                    int retry = 5;
                                    while (retry > 0) {
                                        if (mGlobalVar.tranSet_Value(Transfer_Con.HID_CMD_SET_SCREEN_RESOLUTION, mRes_Wid, mRes_Hei))
                                            break;
                                        retry--;
                                    }
                                }
                            }
                        }


                        if((mGlobalVar.getDeviceIndex()==Transfer_Con.DEVICE_GM1_INDEX)||(mGlobalVar.getDeviceIndex()==Transfer_Con.DEVICE_GM2_INDEX))
                        {
                            if(mRes_Hei>mRes_Wid) {
                                int retry = 5;
                                while(retry>0) {
                                    if(mGlobalVar.tranSet_Value(Transfer_Con.HID_CMD_SET_SCREEN_RESOLUTION, mRes_Hei, mRes_Wid))
                                        break;
                                    retry--;
                                }
                            }
                            else {
                                int retry = 5;
                                while (retry > 0) {
                                    if (mGlobalVar.tranSet_Value(Transfer_Con.HID_CMD_SET_SCREEN_RESOLUTION, mRes_Wid, mRes_Hei))
                                        break;
                                    retry--;
                                }
                            }
                            if(Transfer_Con.ENABLE_GN_LOGO_QUICK_MENU) {
                                mGlobalVar.setIsSupportMenuKey(true);
                            }
                        }
                        if(mGlobalVar.getIsCurDeviceKB())
                        {
                            if(mRes_Hei>mRes_Wid) {
                                int retry = 5;
                                while(retry>0) {
                                    if(mGlobalVar.tranSet_Value(Transfer_Con.HID_CMD_SET_SCREEN_RESOLUTION, mRes_Hei, mRes_Wid))
                                        break;
                                    retry--;
                                }
                            }
                            else {
                                int retry = 5;
                                while (retry > 0) {
                                    if (mGlobalVar.tranSet_Value(Transfer_Con.HID_CMD_SET_SCREEN_RESOLUTION, mRes_Wid, mRes_Hei))
                                        break;
                                    retry--;
                                }
                            }
                            if(mGlobalVar.getIsSupportEditMode_KB())
                                mGlobalVar.tranSet_Value(Transfer_Con.HID_CMD_SET_EDIT_MODE,0,0);
                        }
                        mGlobalVar.InitDeviceButtonIndex();
                        //Log.d(TAG,String.format("gp version: %d,%d",mGlobalVar.get_IntVersion(),checkGPVersion()));
                        /*  // Alex
                        if(checkGPVersion()>mGlobalVar.get_IntVersion())
                        {
                            AlertDialog.Builder builder1 = new AlertDialog.Builder(MainActivity.this);
                            builder1.setTitle("提示")
                                    .setMessage("有新的手柄固件版本，请问是否需要更新？")
                                    .setPositiveButton("马上更新", new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            b_isNeedToUpdate =  true;
                                            showDeviceUpdate();
                                        }
                                    })
                                    .setNegativeButton("以后再说", new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {

                                        }
                                    })
                                    .create().show();
                        }
                        */
                        if(mGlobalVar.getIsCurDeviceKB()&&mGlobalVar.getbIsTransferMode())
                        {
                            if((checkGPVersion()>mGlobalVar.get_IntVersion())&&!bIsReMindToUpdate)
                            {
                                bIsReMindToUpdate = true;
                                AlertDialog.Builder builder1 = new AlertDialog.Builder(MainActivity.this);
                               // String str = String.format("当前版本:%d.%03d.%02d,新的版本:%d.%03d.%02d",mGlobalVar.get_IntVersion() >> 24, (mGlobalVar.get_IntVersion() & 0xFFFFFF) >> 8, mGlobalVar.get_IntVersion() & 0xff,checkGPVersion()>> 24, (checkGPVersion() & 0xFFFFFF) >> 8, checkGPVersion() & 0xff);
                                builder1.setTitle(getResources().getString(R.string.string_app_update_title))
                                        .setMessage(getResources().getString(R.string.string_app_update_query))
                                        .setPositiveButton(getResources().getString(R.string.string_app_go_to_update), new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialog, int which) {
                                                b_isNeedToUpdate =  true;
                                                if(!bIspopupWindowDeviceUpdateShow)
                                                    showDeviceUpdate();
                                            }
                                        })
                                        .setNegativeButton(getResources().getString(R.string.string_app_update_talk_later), new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialog, int which) {

                                            }
                                        })
                                        .create().show();
                            }
                            else if((mGlobalVar.get_IntVersion()>=((1<<24)|(1<<8)|30))&&(checkGPVersion()==mGlobalVar.get_IntVersion())&&!bIsCheckSumDiff)
                            {
                                g_lCodeLen = LoadCode(mGlobalVar.getDeviceName());
                                codeCks = 0;
                                if(g_lCodeLen>0)
                                {
                                    for(int s=0;s<g_lCodeLen;s++)
                                        codeCks += (g_u8CodeBuf[s]&0xff);
                                }
                                if(mGlobalVar.tranGet_Value(Transfer_Con.HID_CMD_GET_CHECKSUM,0x4000,g_lCodeLen,g_u8DataBuf))
                                {
                                    int cks = ((g_u8DataBuf[1]&0xff)<<8)|(g_u8DataBuf[0]&0xff);
                                    if((codeCks&0xffff)!=cks)
                                    {
                                        //Toast.makeText(MainActivity.this,"Checksum Unmatch "+String.format("0x%04X==0x%04X",codeCks,cks),Toast.LENGTH_SHORT).show();
                                        bIsCheckSumDiff = true;
                                        AlertDialog.Builder builder1 = new AlertDialog.Builder(MainActivity.this);
                                        // String str = String.format("当前版本:%d.%03d.%02d,新的版本:%d.%03d.%02d",mGlobalVar.get_IntVersion() >> 24, (mGlobalVar.get_IntVersion() & 0xFFFFFF) >> 8, mGlobalVar.get_IntVersion() & 0xff,checkGPVersion()>> 24, (checkGPVersion() & 0xFFFFFF) >> 8, checkGPVersion() & 0xff);
                                        builder1.setTitle("提示")
                                                .setMessage("固件可能损坏，需要重新烧录，是否前往？")
                                                .setPositiveButton("前往烧录", new DialogInterface.OnClickListener() {
                                                    @Override
                                                    public void onClick(DialogInterface dialog, int which) {
                                                        b_isNeedToUpdate =  true;
                                                        if(!bIspopupWindowDeviceUpdateShow)
                                                            showDeviceUpdate();
                                                    }
                                                })
                                                .setNegativeButton("以后再说", new DialogInterface.OnClickListener() {
                                                    @Override
                                                    public void onClick(DialogInterface dialog, int which) {

                                                    }
                                                })
                                                .create().show();
                                    }
                                }
                            }
                        }



                    }
                    break;
                case TO_CNT_BLE_DEVICE:
                    mProgressDialog.dismiss();
                    if(bluetoothUtils.getBleConnectStatus())
                    {
                        tv_app_status_info_device_name_content.setText(bluetoothUtils.getBleDeviceName());
                        tv_app_status_info_device_ver_content.setText(bluetoothUtils.getBleStrFwVer());
                        iv_connect_mode_cnt_sta.setImageResource(R.drawable.connect);
                    }
                    else
                    {
                        tv_app_status_info_device_name_content.setText(getResources().getString(R.string.string_app_status_info_content_unknown));
                        tv_app_status_info_device_ver_content.setText(getResources().getString(R.string.string_app_status_info_content_unknown));
                        tv_app_status_info_device_connect_content.setText(getResources().getString(R.string.string_pop_connect_disconnect));
                        tv_app_status_info_device_type_content.setText(getResources().getString(R.string.string_app_status_info_content_unknown));
                        tv_app_status_info_device_mode_content.setText(getResources().getString(R.string.string_app_status_info_content_unknown));
                        iv_connect_mode_cnt_sta.setImageResource(R.drawable.disconnect);
                    }
                    break;
                case USBPermitRequest:
                    if(mGlobalVar.myUsbManager==null)
                        return;
                    if(mGlobalVar.myUsbDevice==null)
                        return;
                    if(!mGlobalVar.myUsbManager.hasPermission(mGlobalVar.myUsbDevice))
                    {
                        requestUSBPermit();
                    }
                    else
                    {
                        if(!mGlobalVar.getbIsUsbConnect())
                        {
                            if(mGlobalVar.connectDevice())
                            {
                                //launchLayout.setVisibility(View.GONE);
                                if(mGlobalVar.getDeviceIndex()==Transfer_Con.DEVICE_GM1_INDEX)
                                {
                                    if (mGlobalVar.tranGet_Value(Transfer_Con.HID_CMD_GET_HW_SETTING, 0, 0x84, g_u8DataBuf)) {
                                        if ((g_u8DataBuf[0] & 0x80) == 0x80) {
                                            if((g_u8DataBuf[0] & 0x04) == 0x04) {
                                                mGlobalVar.setIsPC360Mode(true);
                                                mGlobalVar.setIsSimulateMode(true);
                                            }
                                            else {
                                                mGlobalVar.setIsSimulateMode(true);
                                                mGlobalVar.setIsPC360Mode(false);
                                            }
                                        } else {
                                            mGlobalVar.setIsSimulateMode(false);
                                            mGlobalVar.setIsPC360Mode(false);
                                        }
                                    }
                                }
                                else {
                                    mGlobalVar.setIsPC360Mode(false);
                                    if (mGlobalVar.tranGet_Value(Transfer_Con.HID_CMD_GET_HW_SETTING, 0, mGlobalVar.getIsSupportMenuKey() ? 0x80 : 0, g_u8DataBuf)) {
                                        if ((g_u8DataBuf[0] & 0x80) == 0x80) {
                                            mGlobalVar.setIsSimulateMode(true);
                                        } else {
                                            mGlobalVar.setIsSimulateMode(false);
                                        }
                                    }
                                }
                                iv_top_connect.setImageResource(R.drawable.connect);
                                tv_connect_mode_cnt_sta.setText(mGlobalVar.getDeviceName()+getResources().getString(R.string.string_pop_connect_already_connect));
                                iv_connect_mode_cnt_sta.setImageResource(R.drawable.connect);
                                getAllDataAndShow();
                                tv_device_update_version_cur.setText(mGlobalVar.getStrFwVer());
                                if(mGlobalVar.getIsCurDeviceGamePad())
                                    sendSimulateMode();
                                try {
                                    Thread.sleep(100);
                                } catch (InterruptedException e) {
                                    e.printStackTrace();
                                }
                                sendConnectStatus(true,true);
                            }
                        }
                    }
                    break;
                case VERSION_CHECK_NOUPDATE:
                    AlertDialog.Builder builder1 = new AlertDialog.Builder(MainActivity.this);
                    builder1.setTitle(getResources().getString(R.string.string_pop_check_update_result))
                            .setMessage(getResources().getString(R.string.string_pop_check_update_newest))
                            .create().show();
                    break;
                case VERSION_CHECK_UPDATE:
                    AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                    builder.setTitle(getResources().getString(R.string.string_pop_check_update_get_new)+app_info.strVersion)
                            .setMessage(app_info.strDescription)
                            .setPositiveButton(getResources().getString(R.string.string_pop_update), new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    bIsAppCanUpdate = true;
                                    checkAppUpdate();
                                }
                            })
                            .setNegativeButton(getResources().getString(R.string.string_pop_cancel), new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {

                                }
                            }).create().show();
                    break;
                case INJECT_VERIFY_STATUS:
                    if(mInjectVerifyStep>=3)
                    {
                        mInjectVerifyStep = 0;
                        mInjectTimeCounter = 0;
                        bInjectFirstTime = false;
                        bInjectVerifyFail= false;
                        inject_verify_popupWindow.dismiss();
                        Toast.makeText(MainActivity.this,getResources().getString(R.string.string_pop_verify_pass),Toast.LENGTH_SHORT).show();
                        saveUserData(false);
                        break;
                    }
                    if(mInjectTimeCounter>0) {
                        mInjectTimeCounter--;
                        updateInjectVerify();
                        tv_inject_verify_time.setText(String.valueOf(mInjectTimeCounter)+getResources().getString(R.string.string_pop_second));
                    }
                    else
                    {
                        if(mInjectVerifyStep<3)
                        {
                            mInjectVerifyStep = 0;
                            mInjectTimeCounter = 0;
                            bInjectVerifyFail = true;
                            bInjectFirstTime = false;
                            Toast.makeText(MainActivity.this,getResources().getString(R.string.string_pop_verify_fail),Toast.LENGTH_SHORT).show();
                            sendConnectStatus(false,true);
                            rb_connect_mode_inject.setEnabled(true);
                            rb_connect_mode_inject.setChecked(false);
                            rb_connect_mode_normal.setChecked(true);
                            mGlobalVar.setIsInjectMode(false);
                            saveUserData(false);
                        }
                        inject_verify_popupWindow.dismiss();
                    }
                    break;
            }

        }
    };

    public void updateInjectVerify()
    {
        Message msg=new Message();
        msg.what = INJECT_VERIFY_STATUS;
        launchHandler.sendMessageDelayed(msg, 1000);//设置在SPLASHTIME时间后，发送消息
    }

    View statusBarView;
    private void initStatusBar() {
        if (statusBarView == null) {
            //利用反射机制修改状态栏背景
            int identifier = getResources().getIdentifier("statusBarBackground", "id", "android");
            statusBarView = getWindow().findViewById(identifier);
        }
        if (statusBarView != null) {
            statusBarView.setBackgroundResource(R.drawable.shape_title_bg);
        }
    }



    @Override
    public void onClick(View v) {
        ResetImg();

        switch (v.getId()) {
            case R.id.tab_game_list:
                mViewPager.setCurrentItem(0);
                iv_bottom_game.setImageResource(R.drawable.game_sel);
                tv_bottom_game.setTextColor(this.getResources().getColor(R.color.titleEndColor));
                break;
            case R.id.tab_gamepad_setting:
                mViewPager.setCurrentItem(1);
                iv_bottom_gp_setting.setImageResource(R.drawable.gp_setting_sel);
                tv_bottom_gp_setting.setTextColor(this.getResources().getColor(R.color.titleMiddle));
                break;
            case R.id.tab_app_setting:
                mViewPager.setCurrentItem(2);
                iv_bottom_app_setting.setImageResource(R.drawable.app_sel);
                tv_bottom_app_setting.setTextColor(this.getResources().getColor(R.color.titleStartColor));
                break;
            default:
                break;
        }
    }
    @Override
    protected void onStart() {
        super.onStart();
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        Intent intent2 = new Intent(MainActivity.this, SocketRecvService.class);
        stopService(intent2);
        mGlobalVar.setIsSocketRecvServiceRunning(false);
        unregisterReceiver(myBroadcastReceiver);
        handler.removeCallbacks(runnable);
        handler.removeCallbacks(runnableUpdate);
        if(g_bIsRegisterUsbPermitRec)
            unregisterReceiver(mUsbPermissionActionReceiver);
    }

    Runnable runnable=new Runnable() {
        @Override
        public void run() {
            // TODO Auto-generated method stub

            if(mGlobalVar.myUsbDevice==null)
            {
                if(mGlobalVar.enumDevice()>0)
                {
                    if(!mGlobalVar.myUsbManager.hasPermission(mGlobalVar.myUsbDevice))
                        requestUSBPermit();
                }
            }

            if((mGlobalVar.myUsbDevice!=null)&&(mGlobalVar.myUsbManager.hasPermission(mGlobalVar.myUsbDevice)))
            {
                if(mGlobalVar.connectDevice())
                {
                    //launchLayout.setVisibility(View.GONE);
                    iv_top_connect.setImageResource(R.drawable.connect);
                    tv_connect_mode_cnt_sta.setText(mGlobalVar.getDeviceName()+getResources().getString(R.string.string_pop_connect_already_connect));
                    iv_connect_mode_cnt_sta.setImageResource(R.drawable.connect);

                    if(mGlobalVar.getDeviceIndex()==Transfer_Con.DEVICE_GM1_INDEX)
                    {
                        if (mGlobalVar.tranGet_Value(Transfer_Con.HID_CMD_GET_HW_SETTING, 0, 0x84, g_u8DataBuf)) {
                            if ((g_u8DataBuf[0] & 0x80) == 0x80) {
                                if((g_u8DataBuf[0] & 0x04) == 0x04) {
                                    mGlobalVar.setIsPC360Mode(true);
                                    mGlobalVar.setIsSimulateMode(true);
                                }
                                else {
                                    mGlobalVar.setIsSimulateMode(true);
                                    mGlobalVar.setIsPC360Mode(false);
                                }
                            } else {
                                mGlobalVar.setIsSimulateMode(false);
                                mGlobalVar.setIsPC360Mode(false);
                            }
                        }
                    }
                    else {
                        mGlobalVar.setIsPC360Mode(false);
                        if (mGlobalVar.tranGet_Value(Transfer_Con.HID_CMD_GET_HW_SETTING, 0, mGlobalVar.getIsSupportMenuKey() ? 0x80 : 0, g_u8DataBuf)) {
                            if ((g_u8DataBuf[0] & 0x80) == 0x80) {
                                mGlobalVar.setIsSimulateMode(true);
                            } else {
                                mGlobalVar.setIsSimulateMode(false);
                            }
                        }
                    }
                    if(mGlobalVar.getbIsTransferMode()) {

                        getAllDataAndShow();
                        tv_device_update_version_cur.setText(mGlobalVar.getStrFwVer());
                    }
                    if(mGlobalVar.getIsCurDeviceGamePad())
                        sendSimulateMode();
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    sendConnectStatus(true,true);
                    handler.removeCallbacks(runnable);
                }
            }
            else {
                handler.postDelayed(this, 500);
            }
        }
    };

    Runnable runnableUpdate=new Runnable() {
        @Override
        public void run() {
            // TODO Auto-generated method stub
            if(mGlobalVar.connectDevice())
            {
                    //launchLayout.setVisibility(View.GONE);
                    iv_top_connect.setImageResource(R.drawable.connect);
                    handler.removeCallbacks(runnable);
                    UpdateFw();
            }
            else {
                handler.postDelayed(this, 2000);
            }
        }
    };


    public BroadcastReceiver myBroadcastReceiver =new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            boolean bFlag = true;
            String action=intent.getAction();
            Log.d(TAG,"Receiver: "+action);
            if(UsbManager.ACTION_USB_DEVICE_ATTACHED.equals(action)) {
                //Toast.makeText(context,"USB device Connect",Toast.LENGTH_SHORT).show();
                //Log.d("SOE_Rec","USB Connect");
                UsbDevice device = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
                if (device != null) {
                    if (device.getVendorId() == Transfer_Con.VendorID) {

                        if (device.getProductId() == ISPCmd_Con.ProductID) {
                            bFlag=false;
                        } else if ((device.getProductId() == Transfer_Con.ProductID)||(device.getProductId() == Transfer_Con.ProductID_HN2)||(device.getProductId() == Transfer_Con.ProductID_MP1)||(device.getProductId() == Transfer_Con.ProductID_BX1)||(device.getProductId() == Transfer_Con.ProductID_BX2)||(device.getProductId() == Transfer_Con.ProductID_U41)||(device.getProductId() == Transfer_Con.ProductID_MR1)) {
                            bFlag=false;
                        }
                    }
                    else if (device.getVendorId() == Transfer_Con.VendorID_360) {
                        if (device.getProductId() == Transfer_Con.ProductID_360) {
                            bFlag=false;
                        }
                    }
                    else
                    {
                        for(int a=0;a<10;a++)
                        {
                            if (device.getVendorId() == Transfer_Con.u16VIDTable[a])
                            {
                                for(int k=0;k<30;k++)
                                {
                                    if (device.getProductId() == Transfer_Con.u16PIDTable[k])
                                    {
                                        bFlag=false;
                                        break;
                                    }
                                }
                            }
                        }
                    }

                }
                if(bFlag)
                    return;

                mGlobalVar.setbIsUsbConnect(false);
                mGlobalVar.setbIsTransferMode(false);

                if(mGlobalVar.myUsbDevice==null) {
                    mGlobalVar.enumDevice();
                }
                if(mGlobalVar.myUsbDevice!=null)
                {
                      //插入的时候系统会自行进行申请 需要知道系统的广播
                        if(!mGlobalVar.myUsbManager.hasPermission(mGlobalVar.myUsbDevice)) {
                            //requestUSBPermit();
                            //Message msg = new Message();
                            //msg.what = USBPermitRequest;//LAUNCHSCREEN;
                            //launchHandler.sendMessageDelayed(msg, 10000);
                            handler.postDelayed(runnable, 1000);
                        }
                        else if(mGlobalVar.connectDevice())
                        {
                            //Log.d(TAG,"connectDevice ");
                            if(mGlobalVar.getbIsTransferMode()) {

                                getAllDataAndShow();
                                tv_device_update_version_cur.setText(mGlobalVar.getStrFwVer());
                            }
                            //launchLayout.setVisibility(View.GONE);
                            iv_top_connect.setImageResource(R.drawable.connect);
                            tv_connect_mode_cnt_sta.setText(mGlobalVar.getDeviceName()+getResources().getString(R.string.string_pop_connect_already_connect));
                            iv_connect_mode_cnt_sta.setImageResource(R.drawable.connect);

                            if(mGlobalVar.getDeviceIndex()==Transfer_Con.DEVICE_GM1_INDEX)
                            {
                                if (mGlobalVar.tranGet_Value(Transfer_Con.HID_CMD_GET_HW_SETTING, 0, 0x84, g_u8DataBuf)) {
                                    if ((g_u8DataBuf[0] & 0x80) == 0x80) {
                                        if((g_u8DataBuf[0] & 0x04) == 0x04) {
                                            mGlobalVar.setIsPC360Mode(true);
                                            mGlobalVar.setIsSimulateMode(true);
                                        }
                                        else {
                                            mGlobalVar.setIsSimulateMode(true);
                                            mGlobalVar.setIsPC360Mode(false);
                                        }
                                    } else {
                                        mGlobalVar.setIsSimulateMode(false);
                                        mGlobalVar.setIsPC360Mode(false);
                                    }
                                }
                            }
                            else {
                                if (mGlobalVar.tranGet_Value(Transfer_Con.HID_CMD_GET_HW_SETTING, 0,  0x80, g_u8DataBuf)) {
                                    if ((g_u8DataBuf[0] & 0x80) == 0x80) {
                                        mGlobalVar.setIsSimulateMode(true);
                                    } else {
                                        mGlobalVar.setIsSimulateMode(false);
                                    }
                                }
                            }
                            if(mGlobalVar.getIsCurDeviceGamePad())
                                sendSimulateMode();
                            try {
                                Thread.sleep(100);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                            if(mGlobalVar.getbIsTransferMode())
                                sendConnectStatus(true,true);
                        }
                }
            }
            else if(UsbManager.ACTION_USB_DEVICE_DETACHED.equals(action))
            {

                mGlobalVar.setbIsUsbConnect(false);
                mGlobalVar.setbIsTransferMode(false);
                mGlobalVar.myUsbDevice = null;
                mGlobalVar.myInterface = null;
                mGlobalVar.epOut = null;
                mGlobalVar.epIn = null;
                if(!mGlobalVar.connectDevice())
                {
                   // Log.d(TAG,"Usb device remove");
                    sendConnectStatus1(false);
                    mGlobalVar.setIsInjectData(false);
                    iv_top_connect.setImageResource(R.drawable.disconnect);
                    tv_connect_mode_cnt_sta.setText(mGlobalVar.getDeviceName()+getResources().getString(R.string.string_pop_connect_disconnect));
                    mGlobalVar.setStrFwVer("NA");
                    mGlobalVar.clear_IntVersion();
                    tv_device_update_version_cur.setText(mGlobalVar.getStrFwVer());
                    iv_connect_mode_cnt_sta.setImageResource(R.drawable.disconnect);
                    rb_connect_mode_gp_normal.setEnabled(false);
                    rb_connect_mode_gp_touch.setEnabled(false);
                    rb_connect_mode_inject.setEnabled(false);
                    rb_connect_mode_normal.setEnabled(false);
                    myAdapter.notifyDataSetChanged();
                }
            }
        }
    };

    public static boolean isServiceRunning(Context context, String ServiceName) {
        if (TextUtils.isEmpty(ServiceName)) {
            return false;
        }
        ActivityManager myManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        ArrayList<ActivityManager.RunningServiceInfo> runningService = (ArrayList<ActivityManager.RunningServiceInfo>) myManager.getRunningServices(1000);
       // Log.d("SOEMain",String.valueOf(runningService.size()));
        for (int i = 0; i < runningService.size(); i++) {
         //   Log.d("SOEMain",""+runningService.get(i).service.getClassName().toString());
            if (runningService.get(i).service.getClassName().toString().equals(ServiceName)) {
                return true;
            }
        }
        return false;
    }

    private void getAllDataAndShow()
    {
        int temp=0;
        if(!mGlobalVar.getbIsTransferMode())
            return;
        for(int reTry=0;reTry<5;reTry++) {
            temp = mGlobalVar.get_Version(g_u8DataBuf);
            if(temp>0)
                break;
        }
        if(temp>0)
        {
            byte[]data = new byte[temp];
            System.arraycopy(g_u8DataBuf,0,data,0,temp);
            mGlobalVar.setStrFwVer(new String(data));
            //    Log.d(TAG,"Ver: "+ mGlobalVar.getStrFwVer());
        }
        for(int reTry=0;reTry<5;reTry++) {
            temp = mGlobalVar.get_BuildDate(g_u8DataBuf);
            if(temp>0)
                break;
        }
        if(temp>0)
        {
            byte[]data = new byte[temp];
            System.arraycopy(g_u8DataBuf,0,data,0,temp);
            mGlobalVar.setStrBuildDate(new String(data));
            //Log.d(TAG,"Date: "+mGlobalVar.getStrBuildDate());
        }
        bIsConnectedBefore = true;
        for(int reTry=0;reTry<5;reTry++) {
            temp = mGlobalVar.get_DeviceName(g_u8DataBuf);
            if(temp>0)
                break;
        }
        if(temp>0)
        {
            byte[]data = new byte[temp];
            System.arraycopy(g_u8DataBuf,0,data,0,temp);
            mGlobalVar.setDeviceName(new String(data));
            mViewPager.setCurrentItem(0);
            if(mGlobalVar.getDeviceIndex()!=mGlobalVar.getLastConnectDeviceIndex())
            {
                if(!mGlobalVar.getIsDeviceSameType())
                {
                    dataList = new ArrayList<Map<String, Object>>();
                    final PackageManager packageManager = MainActivity.this.getPackageManager();
                    List<PackageInfo> packageInfoList = packageManager.getInstalledPackages(PackageManager.MATCH_UNINSTALLED_PACKAGES);
                    if (packageInfoList != null) {
                        int gameCouter = 0;
                        int defGameNum = 0;

                    if(mGlobalVar.getIsCurDeviceKB())
                    {
                        for (int s = 0; s < (Transfer_Con.MAX_GP_FIX_GAME_NUM + mGlobalVar.getUserGameNum()); s++) {
                            for (int i = 0; i < packageInfoList.size(); i++) {
                                if ((packageInfoList.get(i).applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
                                    continue;
                                }
                                String packName = packageInfoList.get(i).packageName;
                                if (packName.contains(s>=Transfer_Con.MAX_GP_FIX_GAME_NUM?mGlobalVar.getPackageName(s):Transfer_Con.defPackageName[s])) {
                                    Map<String, Object> map = new HashMap<String, Object>();
                                    map.put("id", String.valueOf(gameCouter + 1));
                                    map.put("icn", packageInfoList.get(i).applicationInfo.loadIcon(getPackageManager()));
                                    if (s == 1)
                                        map.put("name", packageInfoList.get(i).applicationInfo.loadLabel(getPackageManager()) + "3" + getResources().getString(R.string.string_pop_game_list_skill));
                                    else if (s == 2)
                                        map.put("name", packageInfoList.get(i).applicationInfo.loadLabel(getPackageManager()) + "4" + getResources().getString(R.string.string_pop_game_list_skill));
                                    else
                                        map.put("name", packageInfoList.get(i).applicationInfo.loadLabel(getPackageManager()));
                                    //map.put("name", (String) packageInfoList.get(i).packageName);
                                    //Log.d(TAG,(String) packageInfoList.get(i).packageName);
                                    map.put("pckname", (String) packageInfoList.get(i).packageName);
                                    map.put("add", R.drawable.plus);
                                    map.put("rev", R.drawable.minus);
                                    map.put("start", getResources().getString(R.string.string_pop_game_list_enter));
                                    if (s < Transfer_Con.MAX_GP_FIX_GAME_NUM) {
                                        defGameNum++;
                                        map.put("type", Transfer_Con.LIST_TYPE_DEF);
                                    } else {
                                        map.put("type", Transfer_Con.LIST_TYPE_USER);
                                    }
                                    dataList.add(map);
                                    gameCouter++;
                                    break;
                                }
                            }
                        }
                        mGlobalVar.setGameDefExist(defGameNum);
                        mGlobalVar.setGameListTotalNum(gameCouter);
                        }
                        else if(mGlobalVar.getIsCurDeviceKB())
                        {
                            for (int s = 0; s < (Transfer_Con.MAX_GP_FIX_GAME_NUM_KB + mGlobalVar.getUserGameNumKB()); s++) {
                                for (int i = 0; i < packageInfoList.size(); i++) {
                                    if ((packageInfoList.get(i).applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
                                        continue;
                                    }

                                    String packName = packageInfoList.get(i).packageName;

                                    if (packName.contains(s>=Transfer_Con.MAX_GP_FIX_GAME_NUM_KB?mGlobalVar.getPackageNameKB(s):Transfer_Con.initPackageName[s])) {
                                        Map<String, Object> map = new HashMap<String, Object>();
                                        map.put("id", String.valueOf(gameCouter + 1));
                                        map.put("icn", packageInfoList.get(i).applicationInfo.loadIcon(getPackageManager()));
                                        map.put("name", packageInfoList.get(i).applicationInfo.loadLabel(getPackageManager()));
                                        //map.put("name", (String) packageInfoList.get(i).packageName);
                                        //Log.d(TAG,(String) packageInfoList.get(i).packageName);
                                        map.put("pckname", (String) packageInfoList.get(i).packageName);
                                        map.put("add", R.drawable.plus);
                                        map.put("rev", R.drawable.minus);
                                        map.put("start", getResources().getString(R.string.string_pop_game_list_enter));
                                        if (s < Transfer_Con.MAX_GP_FIX_GAME_NUM_KB) {
                                            defGameNum++;
                                            map.put("type", Transfer_Con.LIST_TYPE_DEF);
                                        } else {
                                            map.put("type", Transfer_Con.LIST_TYPE_USER);
                                        }
                                        dataList.add(map);
                                        gameCouter++;
                                        break;
                                    }
                                }
                            }
                            Log.d(TAG,String.format("aaaaaaaaaaaa def=%d, tot=%d",defGameNum,gameCouter));
                            mGlobalVar.setGameDefExistKB(defGameNum);
                            mGlobalVar.setGameListTotalNumKB(gameCouter);
                        }
                        if(Transfer_Con.ENABLE_GAME_DATA_IN_PHONE_GP)
                        {
                            if (dataList.size() < Transfer_Con.MAX_GAME_NUM_IN_PHONE)
                            {
                                Map<String, Object> map = new HashMap<String, Object>();
                                map.put("id", String.valueOf(dataList.size() + 1));
                                //map.put("name", (String) packageInfoList.get(i).packageName);
                                //map.put("pckname", (String) packageInfoList.get(a).packageName);
                                map.put("add", R.drawable.plus);
                                map.put("rev", R.drawable.minus);
                                map.put("type", Transfer_Con.LIST_TYPE_NULL);
                                //map.put("start", "Start");
                                dataList.add(map);
                            }
                        }
                        else {
                            if (dataList.size() < Transfer_Con.MAX_GAME_NUM) {
                                for (int a = dataList.size(); a < Transfer_Con.MAX_GAME_NUM; a++) {
                                    Map<String, Object> map = new HashMap<String, Object>();
                                    map.put("id", String.valueOf(a + 1));
                                    //map.put("name", (String) packageInfoList.get(i).packageName);
                                    //map.put("pckname", (String) packageInfoList.get(a).packageName);
                                    map.put("add", R.drawable.plus);
                                    map.put("rev", R.drawable.minus);
                                    map.put("type", Transfer_Con.LIST_TYPE_NULL);
                                    //map.put("start", "Start");
                                    dataList.add(map);
                                }
                            }
                        }
                        //Log.d(TAG,"aaaaaaaaaaaaaaaa  Size = "+String.valueOf(dataList.size()));
                        myAdapter = new MyAdapter(this);
                        lv_gamelist.setAdapter(myAdapter);
                    }
                }
                mGlobalVar.setLastConnectDeviceIndex(mGlobalVar.getDeviceIndex());
                saveUserData(false);
            }
        }

        if(mGlobalVar.getIsCurDeviceGamePad()) {
            if (mGlobalVar.get_CurPhone(g_u8DataBuf)) {
                mGlobalVar.setmCurPhone(g_u8DataBuf[0]);
                if (g_u8DataBuf[0] < Transfer_Con.MAX_PHONE_NUM) {
                    int phone = getResolutionIndex();
                    if (phone != g_u8DataBuf[0]) {
                        if (mGlobalVar.tranSet_Value(Transfer_Con.HID_CMD_SET_PHONE_CUR, phone, 0)) {
                            mGlobalVar.setmCurPhone(phone);
                        }
                        if (!resolutionCompare()) {
                            AlertDialog.Builder builder = new AlertDialog.Builder(this);
                            builder.setTitle(getResources().getString(R.string.string_pop_reminder))
                                    .setMessage(getResources().getString(R.string.string_pop_reminder_screen_size))
                                    .setPositiveButton(getResources().getString(R.string.string_pop_confirm), new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                        }
                                    }).create().show();
                        }
                    }
                }
            }
            if (mGlobalVar.get_CurGame(g_u8DataBuf)) {
                //mCurGame = g_u8DataBuf[0];
                //Log.d(TAG,"Game: "+String.valueOf(g_u8DataBuf[0]));
                if (g_u8DataBuf[0] >= (mGlobalVar.getUserGameNum() + Transfer_Con.MAX_GP_FIX_GAME_NUM)) {
                    mGlobalVar.tranSet_Value(Transfer_Con.HID_CMD_SET_GAME_CUR, 0, 0);
                    mGlobalVar.setmCurGame(0);
                } else
                    mGlobalVar.setmCurGame(g_u8DataBuf[0]);
                //if(mGlobalVar.getmCurGame()<Transfer_Con.MAX_GP_FIX_GAME_NUM)
                //    tv_setting_new_game_cur.setText(Transfer_Con.GameName[mGlobalVar.getmCurGame()]);
                //else
                //    tv_setting_new_game_cur.setText(mGlobalVar.getUserGameName(mGlobalVar.getmCurGame()-Transfer_Con.MAX_GP_FIX_GAME_NUM));
            }
        }
    }

    LinearLayout device_button_setting_kb_tvmode_layout,device_button_setting_kb_force_2touch_layout,device_button_setting_kb_virtual_mouse_layout,device_button_setting_kb_rocker_range_layout,device_button_setting_kb_switch_to_mouse_layout,device_button_setting_kb_audio_layout;
    RelativeLayout device_button_setting_kb_tvmode_manual_layout,device_button_setting_kb_virtual_mouse_speed_layout;
    LinearLayout layout_device_button_setting_kb_tvmode_resolution,layout_device_button_setting_kb_switch_to_mouse;
    Switch sw_device_button_setting_kb_tvmode,sw_device_button_setting_kb_tvmode_auto,sw_device_button_setting_kb_force_2touch,sw_device_button_setting_kb_virtual_mouse;
    SeekBar sb_device_button_setting_kb_rocker_range_value,sb_device_button_setting_kb_virtual_mouse_speed;
    TextView tv_device_button_setting_kb_tvmode_manual_value,tv_device_button_setting_kb_tvmode_auto_value,tv_device_button_setting_kb_tvmode_resolution,tv_device_button_setting_kb_virtual_mouse_speed_value,tv_device_button_setting_kb_rocker_range_value;
    EditText et_device_button_setting_kb_width,et_device_button_setting_kb_height;
    ImageView iv_device_button_setting_kb_btn;
    CheckBox cb_device_button_setting_kb_audio,cb_device_button_setting_kb_switch_to_mouse_press;


    LinearLayout device_button_setting_menu_layout,device_button_setting_gyro_layout,layout_g_sensor_sense,device_button_setting_tvmode_layout,device_button_setting_posswap_layout,device_button_setting_l3r3_layout,device_button_setting_rocker_setting_swap_layout,device_button_setting_rocker_setting_r_rock_range,device_button_setting_rocker_setting_sense_layout,device_button_setting_brake_gas_layout;
    Switch sw_device_button_setting_menu,sw_device_button_setting_gyro,sw_device_button_setting_tvmode,sw_device_button_setting_powswap;
    RadioButton rb_device_button_setting_cz,rb_device_button_setting_l3r3;
    SeekBar sb_g_sensor_y,sb_g_sensor_x,sb_rocker_setting_min,sb_rocker_setting_max,sb_rocker_setting_time,sb_rocker_setting_left_range;
    TextView tv_g_sensor_test_value_x,tv_g_sensor_test_value_y,tv_rocker_setting_left_range,tv_rocker_setting_min_value,tv_rocker_setting_max_value,tv_rocker_setting_time_value;
    ImageView iv_rocker_setting_min_del,iv_rocker_setting_min_add,iv_rocker_setting_max_del,iv_rocker_setting_max_add,iv_rocker_setting_time_del,iv_rocker_setting_time_add;
    CheckBox ckb_rocker_setting_swap,ckb_rocker_setting_left_ups,cb_device_button_setting_brake_gas;
    RadioButton rb_rocker_setting_r_rocker_range_full,rb_rocker_setting_r_rocker_range_limited;
    RelativeLayout device_button_setting_rocker_setting_left_ups,device_button_setting_rocker_setting_left_range;

    private void InitView() {
        // TODO Auto-generated method stub
        mViewPager = (ViewPager) findViewById(R.id.id_viewPager);
        //tabs
        mGameList = (LinearLayout) findViewById(R.id.tab_game_list);
        mGamePadSetting = (LinearLayout) findViewById(R.id.tab_gamepad_setting);
        layout_app_setting = (LinearLayout) findViewById(R.id.tab_app_setting);
        // TextView
        tv_bottom_game = (TextView) findViewById(R.id.tv_bottom_game);
        tv_bottom_gp_setting = (TextView) findViewById(R.id.tv_bottom_gp_setting);
        tv_bottom_app_setting = (TextView) findViewById(R.id.tv_bottom_app_setting);
        //ImageButton
        iv_bottom_game = (ImageView) findViewById(R.id.iv_bottom_game);
        iv_bottom_gp_setting = (ImageView) findViewById(R.id.iv_bottom_gp_setting);
        iv_bottom_app_setting = (ImageView) findViewById(R.id.iv_bottom_app_setting);
        iv_top_connect = (ImageView) findViewById(R.id.iv_top_connect);
        LayoutInflater mInflater = LayoutInflater.from(this);
        g_u8DataBuf = new byte[Transfer_Con.HID_PACKET_SIZE];
        g_u8CodeBuf = new byte[Transfer_Con.HID_PACKET_SIZE];
        m_CONFIG =  new long[4];
        m_CONFIG_User =  new long[4];
        g_lCodeLen = g_lDataLen = 0;
        int resourceId = this.getResources().getIdentifier("status_bar_height", "dimen", "android");
        int result = 0;
        if (resourceId > 0) {
            result = this.getResources().getDimensionPixelSize(resourceId);
        }
        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getRealMetrics(dm);

        if(dm.heightPixels>dm.widthPixels) {
            mRes_Wid = dm.widthPixels;
            mRes_Hei = dm.heightPixels;
        }
        else
        {
            mRes_Hei = dm.widthPixels;
            mRes_Wid = dm.heightPixels;
        }
        mGlobalVar.setScreenWidth(mRes_Wid);
        mGlobalVar.setScreenHeight(mRes_Hei);
        Log.d(TAG,String.format("Screen1=%dX%d",mRes_Wid,mRes_Hei));

        //Log.d(TAG,String.format("Screen2=%dX%d", Resources.getSystem().getDisplayMetrics().widthPixels,Resources.getSystem().getDisplayMetrics().heightPixels));
        //Log.d(TAG,"result="+String.valueOf(result));

        //mRes_Wid = Resources.getSystem().getDisplayMetrics().widthPixels;
        //mRes_Hei = Resources.getSystem().getDisplayMetrics().heightPixels + result;
        //resolutionCompare();
        /*
        ViewGroup.LayoutParams lp = iv_launch_view.getLayoutParams();
        float fRatio = (float)mRes_Hei / mRes_Wid;
        Log.d(TAG,"hei:"+String.valueOf(lp.height)+"R:"+String.valueOf(fRatio));
        lp.height = (int)(fRatio * lp.height  / 2.15f);
        Log.d(TAG,"hei1:"+String.valueOf(lp.height));
        iv_launch_view.setLayoutParams(lp);
        */
        if(!mGlobalVar.connectDevice())
        {
            if(bluetoothUtils.connectDevices()) {
                if(bluetoothUtils.getBleDeviceName().equals("SOE Touch"))
                {
                    Message msg = new Message();
                     msg.what = TO_CNT_BLE_DEVICE;
                    launchHandler.sendMessageDelayed(msg, 1000);//设置在SPLASHTIME时间后，发送消息
                    bluetoothUtils.getDeviceInfo();
                    bluetoothUtils.getDeviceVersion();
                    bluetoothUtils.getDeviceCodeDate();
                    iv_top_connect.setImageResource(R.drawable.connect);
                }
            }
            else
            {
                if (mGlobalVar.getIsLogOn())
                    Log.d(TAG, "connect device fail");
            }
        }
        else
        {
            //launchLayout.setVisibility(View.GONE);
            if(mGlobalVar.getbIsTransferMode())
            {
                if(mGlobalVar.getIsLogOn())
                    Log.d(TAG,"Usb transfer mode");
                if(mGlobalVar.Check_Connect(g_u8DataBuf))
                {
                    if(mGlobalVar.getDeviceIndex()==Transfer_Con.DEVICE_GM1_INDEX)
                    {
                        if (mGlobalVar.tranGet_Value(Transfer_Con.HID_CMD_GET_HW_SETTING, 0, 0x84, g_u8DataBuf)) {
                            if ((g_u8DataBuf[0] & 0x80) == 0x80) {
                                if((g_u8DataBuf[0] & 0x04) == 0x04) {
                                    mGlobalVar.setIsPC360Mode(true);
                                    mGlobalVar.setIsSimulateMode(true);
                                }
                                else {
                                    mGlobalVar.setIsSimulateMode(true);
                                    mGlobalVar.setIsPC360Mode(false);
                                }
                            } else {
                                mGlobalVar.setIsSimulateMode(false);
                                mGlobalVar.setIsPC360Mode(false);
                            }
                        }
                    }
                    else {
                        mGlobalVar.setIsPC360Mode(false);
                        if (mGlobalVar.tranGet_Value(Transfer_Con.HID_CMD_GET_HW_SETTING, 0, mGlobalVar.getIsSupportMenuKey() ? 0x80 : 0, g_u8DataBuf)) {
                            if ((g_u8DataBuf[0] & 0x80) == 0x80) {
                                mGlobalVar.setIsSimulateMode(true);
                            } else {
                                mGlobalVar.setIsSimulateMode(false);
                            }
                        }
                    }
                    if(mGlobalVar.getIsLogOn())
                        Log.d(TAG,"Usb check connect ok");
                    iv_top_connect.setImageResource(R.drawable.connect);
                    if(mGlobalVar.getIsCurDeviceGamePad())
                        sendSimulateMode();
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    sendConnectStatus(true,true);
                    //getInjectStatus();
                }
            }
        }
        iv_top_connect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(!mGlobalVar.getbIsUsbConnect())
                {
                    if(mGlobalVar.myUsbDevice==null) {
                        mGlobalVar.enumDevice();
                    }
                    if(mGlobalVar.myUsbDevice!=null){
                        if(!mGlobalVar.myUsbManager.hasPermission(mGlobalVar.myUsbDevice))
                            requestUSBPermit();
                        else if(mGlobalVar.connectDevice())
                        {
                            launchLayout.setVisibility(View.GONE);
                            if(mGlobalVar.getDeviceIndex()==Transfer_Con.DEVICE_GM1_INDEX)
                            {
                                if (mGlobalVar.tranGet_Value(Transfer_Con.HID_CMD_GET_HW_SETTING, 0, 0x84, g_u8DataBuf)) {
                                    if ((g_u8DataBuf[0] & 0x80) == 0x80) {
                                        if((g_u8DataBuf[0] & 0x04) == 0x04) {
                                            mGlobalVar.setIsPC360Mode(true);
                                            mGlobalVar.setIsSimulateMode(true);
                                        }
                                        else {
                                            mGlobalVar.setIsSimulateMode(true);
                                            mGlobalVar.setIsPC360Mode(false);
                                        }
                                    } else {
                                        mGlobalVar.setIsSimulateMode(false);
                                        mGlobalVar.setIsPC360Mode(false);
                                    }
                                }
                            }
                            else {
                                mGlobalVar.setIsPC360Mode(false);
                                if (mGlobalVar.tranGet_Value(Transfer_Con.HID_CMD_GET_HW_SETTING, 0, mGlobalVar.getIsSupportMenuKey() ? 0x80 : 0, g_u8DataBuf)) {
                                    if ((g_u8DataBuf[0] & 0x80) == 0x80) {
                                        mGlobalVar.setIsSimulateMode(true);
                                    } else {
                                        mGlobalVar.setIsSimulateMode(false);
                                    }
                                }
                            }
                            iv_top_connect.setImageResource(R.drawable.connect);
                            getAllDataAndShow();
                            if(mGlobalVar.getIsCurDeviceGamePad())
                                sendSimulateMode();
                            try {
                                Thread.sleep(100);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                            sendConnectStatus(true,true);
                            //getInjectStatus();
                        }
                        else if(bluetoothUtils.connectDevices())
                        {
                            if(bluetoothUtils.getBleDeviceName().equals("SOE Touch"))
                            {
                                mProgressDialog.create();
                                mProgressDialog.show();
                                Message msg = new Message();
                                msg.what = TO_CNT_BLE_DEVICE;
                                launchHandler.sendMessageDelayed(msg, 1000);//设置在SPLASHTIME时间后，发送消息
                                bluetoothUtils.getDeviceInfo();
                                bluetoothUtils.getDeviceVersion();
                                bluetoothUtils.getDeviceCodeDate();
                                iv_top_connect.setImageResource(R.drawable.connect);
                            }
                        }
                    }
                }
            }
        });
        View tabGameList,tabGpSetting,tabAppSetting;
        tabGameList = mInflater.inflate(R.layout.gamelist_layout, null);
        lv_gamelist = tabGameList.findViewById(R.id.gv_game_list);
        dataList = new ArrayList<Map<String, Object>>();
        final PackageManager packageManager = MainActivity.this.getPackageManager();
        List<PackageInfo> packageInfoList = packageManager.getInstalledPackages(PackageManager.MATCH_UNINSTALLED_PACKAGES);
        if(!bIsConnectedBefore)
        {
            //Log.d(TAG,"---------------------------------->");
            int gameCouter = 0;
            if (packageInfoList != null) {

                for (int i = 0; i < packageInfoList.size(); i++) {
                    if ((packageInfoList.get(i).applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
                        continue;
                    }
                    String packName = packageInfoList.get(i).packageName;
                    if(packName.contains(Transfer_Con.initPackageName[0]))
                    {
                        Map<String, Object> map = new HashMap<String, Object>();
                        map.put("id", String.valueOf(gameCouter+1));
                        map.put("icn", packageInfoList.get(i).applicationInfo.loadIcon(getPackageManager()));
                        map.put("name", packageInfoList.get(i).applicationInfo.loadLabel(getPackageManager()));
                        //map.put("name", (String) packageInfoList.get(i).packageName);
                        //Log.d(TAG,(String) packageInfoList.get(i).packageName);
                        map.put("pckname", (String) packageInfoList.get(i).packageName);
                        map.put("add", R.drawable.plus);
                        map.put("rev", R.drawable.minus);
                        map.put("start", getResources().getString(R.string.string_pop_game_list_enter));
                        map.put("type", Transfer_Con.LIST_TYPE_DEF);
                        gameCouter++;
                        dataList.add(map);
                    }
                }
                mGlobalVar.setGameDefExist(gameCouter);
                mGlobalVar.setGameListTotalNum(gameCouter);
            }
        }
        else {
            if (packageInfoList != null) {
                int gameCouter = 0;
                int defGameNum = 0;

                if(mGlobalVar.getIsCurDeviceKB())
                {
                    for (int s = 0; s < (Transfer_Con.MAX_GP_FIX_GAME_NUM_KB + mGlobalVar.getUserGameNumKB()); s++) {
                        for (int i = 0; i < packageInfoList.size(); i++) {
                            if ((packageInfoList.get(i).applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
                                continue;
                            }

                            String packName = packageInfoList.get(i).packageName;
                            if (packName.contains(s>=Transfer_Con.MAX_GP_FIX_GAME_NUM_KB?mGlobalVar.getPackageNameKB(s):Transfer_Con.initPackageName[s])) {
                                Map<String, Object> map = new HashMap<String, Object>();
                                map.put("id", String.valueOf(gameCouter + 1));
                                map.put("icn", packageInfoList.get(i).applicationInfo.loadIcon(getPackageManager()));
                                map.put("name", packageInfoList.get(i).applicationInfo.loadLabel(getPackageManager()));
                                //map.put("name", (String) packageInfoList.get(i).packageName);
                                //Log.d(TAG,(String) packageInfoList.get(i).packageName);
                                map.put("pckname", (String) packageInfoList.get(i).packageName);
                                map.put("add", R.drawable.plus);
                                map.put("rev", R.drawable.minus);
                                map.put("start", getResources().getString(R.string.string_pop_game_list_enter));
                                if (s < Transfer_Con.MAX_GP_FIX_GAME_NUM_KB) {
                                    defGameNum++;
                                    map.put("type", Transfer_Con.LIST_TYPE_DEF);
                                } else {
                                    map.put("type", Transfer_Con.LIST_TYPE_USER);
                                }
                                dataList.add(map);
                                gameCouter++;
                                break;
                            }
                        }
                    }
                    mGlobalVar.setGameDefExistKB(defGameNum);
                    mGlobalVar.setGameListTotalNumKB(gameCouter);
                    //Log.d(TAG,String.format("bbbbbbbbbbbbbbbb def=%d, tot=%d",defGameNum,gameCouter));
                }
                else {
                    for (int s = 0; s < (Transfer_Con.MAX_GP_FIX_GAME_NUM + mGlobalVar.getUserGameNum()); s++) {
                        for (int i = 0; i < packageInfoList.size(); i++) {
                            if ((packageInfoList.get(i).applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
                                continue;
                            }

                            String packName = packageInfoList.get(i).packageName;

                            if (packName.contains(s>=Transfer_Con.MAX_GP_FIX_GAME_NUM?mGlobalVar.getPackageName(s):Transfer_Con.defPackageName[s])) {
                                Map<String, Object> map = new HashMap<String, Object>();
                                map.put("id", String.valueOf(gameCouter + 1));
                                map.put("icn", packageInfoList.get(i).applicationInfo.loadIcon(getPackageManager()));
                                if (s == 1)
                                    map.put("name", packageInfoList.get(i).applicationInfo.loadLabel(getPackageManager()) + "3" + getResources().getString(R.string.string_pop_game_list_skill));
                                else if (s == 2)
                                    map.put("name", packageInfoList.get(i).applicationInfo.loadLabel(getPackageManager()) + "4" + getResources().getString(R.string.string_pop_game_list_skill));
                                else
                                    map.put("name", packageInfoList.get(i).applicationInfo.loadLabel(getPackageManager()));
                                //map.put("name", (String) packageInfoList.get(i).packageName);
                                //Log.d(TAG,(String) packageInfoList.get(i).packageName);
                                map.put("pckname", (String) packageInfoList.get(i).packageName);
                                map.put("add", R.drawable.plus);
                                map.put("rev", R.drawable.minus);
                                map.put("start", getResources().getString(R.string.string_pop_game_list_enter));
                                if (s < Transfer_Con.MAX_GP_FIX_GAME_NUM) {
                                    defGameNum++;
                                    map.put("type", Transfer_Con.LIST_TYPE_DEF);
                                } else {
                                    map.put("type", Transfer_Con.LIST_TYPE_USER);
                                }
                                dataList.add(map);
                                gameCouter++;
                                break;
                            }
                        }
                    }
                    mGlobalVar.setGameDefExist(defGameNum);
                    mGlobalVar.setGameListTotalNum(gameCouter);
                }
            }
        }
        if(Transfer_Con.ENABLE_GAME_DATA_IN_PHONE_GP)
        {
            if (dataList.size() < Transfer_Con.MAX_GAME_NUM_IN_PHONE)
            {
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("id", String.valueOf(dataList.size() + 1));
                //map.put("name", (String) packageInfoList.get(i).packageName);
                //map.put("pckname", (String) packageInfoList.get(a).packageName);
                map.put("add", R.drawable.plus);
                map.put("rev", R.drawable.minus);
                map.put("type", Transfer_Con.LIST_TYPE_NULL);
                //map.put("start", "Start");
                dataList.add(map);
            }
        }
        else {
            if (dataList.size() < Transfer_Con.MAX_GAME_NUM) {
                for (int a = dataList.size(); a < Transfer_Con.MAX_GAME_NUM; a++) {
                    Map<String, Object> map = new HashMap<String, Object>();
                    map.put("id", String.valueOf(a + 1));
                    //map.put("name", (String) packageInfoList.get(i).packageName);
                    //map.put("pckname", (String) packageInfoList.get(a).packageName);
                    map.put("add", R.drawable.plus);
                    map.put("rev", R.drawable.minus);
                    map.put("type", Transfer_Con.LIST_TYPE_NULL);
                    //map.put("start", "Start");
                    dataList.add(map);
                }
            }
        }
        //Log.d(TAG,"bbbbbbbbbbbb   Size = "+String.valueOf(dataList.size()));
        myAdapter = new MyAdapter(this);
        lv_gamelist.setAdapter(myAdapter);

        if(Transfer_Con.ENABLE_NEW_USER_INTERFACE)
        {
            tabGpSetting = mInflater.inflate(R.layout.main_setting_new_layout, null);
            device_button_setting_kb_tvmode_layout= tabGpSetting.findViewById(R.id.device_button_setting_kb_tvmode_layout);
            device_button_setting_kb_force_2touch_layout= tabGpSetting.findViewById(R.id.device_button_setting_kb_force_2touch_layout);
            device_button_setting_kb_virtual_mouse_layout= tabGpSetting.findViewById(R.id.device_button_setting_kb_virtual_mouse_layout);
            device_button_setting_kb_rocker_range_layout= tabGpSetting.findViewById(R.id.device_button_setting_kb_rocker_range_layout);
            device_button_setting_kb_switch_to_mouse_layout= tabGpSetting.findViewById(R.id.device_button_setting_kb_switch_to_mouse_layout);
            device_button_setting_kb_audio_layout = tabGpSetting.findViewById(R.id.device_button_setting_kb_audio_layout);
            iv_device_button_setting_kb_btn =tabGpSetting.findViewById(R.id.iv_device_button_setting_kb_btn);
            device_button_setting_kb_tvmode_layout = tabGpSetting.findViewById(R.id.device_button_setting_kb_tvmode_layout);
            layout_device_button_setting_kb_switch_to_mouse = tabGpSetting.findViewById(R.id.layout_device_button_setting_kb_switch_to_mouse);
            layout_device_button_setting_kb_tvmode_resolution = tabGpSetting.findViewById(R.id.layout_device_button_setting_kb_tvmode_resolution);
            device_button_setting_kb_tvmode_manual_layout = tabGpSetting.findViewById(R.id.device_button_setting_kb_tvmode_manual_layout);
            sw_device_button_setting_kb_tvmode = tabGpSetting.findViewById(R.id.sw_device_button_setting_kb_tvmode);
            sw_device_button_setting_kb_tvmode_auto = tabGpSetting.findViewById(R.id.sw_device_button_setting_kb_tvmode_auto);
            tv_device_button_setting_kb_tvmode_manual_value = tabGpSetting.findViewById(R.id.tv_device_button_setting_kb_tvmode_manual_value);
            tv_device_button_setting_kb_tvmode_auto_value = tabGpSetting.findViewById(R.id.tv_device_button_setting_kb_tvmode_auto_value);
            et_device_button_setting_kb_width = tabGpSetting.findViewById(R.id.et_device_button_setting_kb_width);
            et_device_button_setting_kb_height = tabGpSetting.findViewById(R.id.et_device_button_setting_kb_height);
            tv_device_button_setting_kb_tvmode_resolution = tabGpSetting.findViewById(R.id.tv_device_button_setting_kb_tvmode_resolution);
            device_button_setting_kb_rocker_range_layout = tabGpSetting.findViewById(R.id.device_button_setting_kb_rocker_range_layout);
            device_button_setting_kb_force_2touch_layout = tabGpSetting.findViewById(R.id.device_button_setting_kb_force_2touch_layout);
            sb_device_button_setting_kb_rocker_range_value = tabGpSetting.findViewById(R.id.sb_device_button_setting_kb_rocker_range_value);
            tv_device_button_setting_kb_rocker_range_value = tabGpSetting.findViewById(R.id.tv_device_button_setting_kb_rocker_range_value);
            sw_device_button_setting_kb_force_2touch = tabGpSetting.findViewById(R.id.sw_device_button_setting_kb_force_2touch);
            device_button_setting_kb_virtual_mouse_layout = tabGpSetting.findViewById(R.id.device_button_setting_kb_virtual_mouse_layout);
            sw_device_button_setting_kb_virtual_mouse = tabGpSetting.findViewById(R.id.sw_device_button_setting_kb_virtual_mouse);
            device_button_setting_kb_virtual_mouse_speed_layout = tabGpSetting.findViewById(R.id.device_button_setting_kb_virtual_mouse_speed_layout);
            sb_device_button_setting_kb_virtual_mouse_speed = tabGpSetting.findViewById(R.id.sb_device_button_setting_kb_virtual_mouse_speed);
            tv_device_button_setting_kb_virtual_mouse_speed_value = tabGpSetting.findViewById(R.id.tv_device_button_setting_kb_virtual_mouse_speed_value);
            cb_device_button_setting_kb_audio = tabGpSetting.findViewById(R.id.cb_device_button_setting_kb_audio);
            cb_device_button_setting_kb_switch_to_mouse_press  = tabGpSetting.findViewById(R.id.cb_device_button_setting_kb_switch_to_mouse_press);

            final Handler handler = new Handler();
            final Runnable delayRun = new Runnable() {
                @Override
                public void run() {
                    String defStr = String.valueOf(mGlobalVar.getManualHDMIWidth());
                    if (!android.text.TextUtils.isEmpty(et_device_button_setting_kb_width.getText()))
                        defStr = et_device_button_setting_kb_width.getText().toString();
                    local_width = Integer.parseInt(defStr);

                    defStr = String.valueOf(mGlobalVar.getManualHDMIHeight());
                    if (!android.text.TextUtils.isEmpty(et_device_button_setting_kb_height.getText()))
                        defStr = et_device_button_setting_kb_height.getText().toString();
                    local_height = Integer.parseInt(defStr);

                    mGlobalVar.setManualSetHDMIWidth(local_width);
                    mGlobalVar.setManualSetHDMIHeight(local_height);
                }
            };

            et_device_button_setting_kb_width.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                }

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {

                }

                @Override
                public void afterTextChanged(Editable s) {
                    if(delayRun!=null){
                        //每次editText有变化的时候，则移除上次发出的延迟线程
                        handler.removeCallbacks(delayRun);
                    }
                    //延迟600ms，如果不再输入字符，则执行该线程的run方法
                    handler.postDelayed(delayRun, 1000);
                }
            });

            et_device_button_setting_kb_height.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                }

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {

                }

                @Override
                public void afterTextChanged(Editable s) {
                    if(delayRun!=null){
                        //每次editText有变化的时候，则移除上次发出的延迟线程
                        handler.removeCallbacks(delayRun);
                    }
                    //延迟600ms，如果不再输入字符，则执行该线程的run方法
                    handler.postDelayed(delayRun, 1000);
                }
            });


            sw_device_button_setting_kb_tvmode.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    if(isChecked)
                    {
                        String defStr = String.valueOf(mGlobalVar.getManualHDMIWidth());
                        if (!android.text.TextUtils.isEmpty(et_device_button_setting_kb_width.getText()))
                            defStr = et_device_button_setting_kb_width.getText().toString();
                        local_width = Integer.parseInt(defStr);

                        defStr = String.valueOf(mGlobalVar.getManualHDMIHeight());
                        if (!android.text.TextUtils.isEmpty(et_device_button_setting_kb_height.getText()))
                            defStr = et_device_button_setting_kb_height.getText().toString();
                        local_height = Integer.parseInt(defStr);

                        mGlobalVar.setManualSetHDMIWidth(local_width);
                        mGlobalVar.setManualSetHDMIHeight(local_height);

                        mGlobalVar.tranSet_Value(Transfer_Con.HID_CMD_SET_HW_SETTING,  0x04, 0x04);
                        mGlobalVar.tranSet_Value(Transfer_Con.HID_CMD_SET_HDMI_RESOLUTION, local_width, local_height);
                        tv_device_button_setting_kb_tvmode_manual_value.setText(getResources().getString(R.string.str_device_button_setting_kb_screen_projection));
                    }
                    else
                    {
                        mGlobalVar.tranSet_Value(Transfer_Con.HID_CMD_SET_HW_SETTING,  0x00, 0x04);
                        tv_device_button_setting_kb_tvmode_manual_value.setText(getResources().getString(R.string.str_device_button_setting_kb_mobile));
                    }
                    mGlobalVar.setIsManualSetToHDMI(isChecked);
                    saveUserData(false);
                }
            });

            sw_device_button_setting_kb_tvmode_auto.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    mGlobalVar.setIsAutoSwitchToHDMI(isChecked);
                    if(isChecked) {
                        tv_device_button_setting_kb_tvmode_auto_value.setText(getResources().getString(R.string.str_device_button_setting_kb_auto));
                        sw_device_button_setting_kb_tvmode.setEnabled(false);
                        tv_device_button_setting_kb_tvmode_manual_value.setEnabled(false);
                        layout_device_button_setting_kb_tvmode_resolution.setVisibility(View.GONE);
                        if(getIsHDMIOut())
                        {
                            sw_device_button_setting_kb_tvmode.setChecked(true);
                            mGlobalVar.tranSet_Value(Transfer_Con.HID_CMD_SET_HDMI_RESOLUTION, local_width, local_height);
                            mGlobalVar.tranSet_Value(Transfer_Con.HID_CMD_SET_HW_SETTING,  0x04, 0x04);
                            tv_device_button_setting_kb_tvmode_manual_value.setText(getResources().getString(R.string.str_device_button_setting_kb_screen_projection));
                        }
                        else
                        {
                            sw_device_button_setting_kb_tvmode.setChecked(false);
                            mGlobalVar.tranSet_Value(Transfer_Con.HID_CMD_SET_HW_SETTING,  0x00, 0x04);
                            tv_device_button_setting_kb_tvmode_manual_value.setText(getResources().getString(R.string.str_device_button_setting_kb_mobile));
                        }
                    }
                    else {
                        getIsHDMIOut();
                        tv_device_button_setting_kb_tvmode_auto_value.setText(getResources().getString(R.string.str_device_button_setting_kb_manual));
                        sw_device_button_setting_kb_tvmode.setEnabled(true);
                        tv_device_button_setting_kb_tvmode_manual_value.setEnabled(true);
                        layout_device_button_setting_kb_tvmode_resolution.setVisibility(View.VISIBLE);
                        if(sw_device_button_setting_kb_tvmode.isChecked()) {
                            mGlobalVar.tranSet_Value(Transfer_Con.HID_CMD_SET_HDMI_RESOLUTION, mGlobalVar.getManualHDMIWidth(), mGlobalVar.getManualHDMIHeight());
                            mGlobalVar.tranSet_Value(Transfer_Con.HID_CMD_SET_HW_SETTING, 0x04, 0x04);
                            tv_device_button_setting_kb_tvmode_manual_value.setText(getResources().getString(R.string.str_device_button_setting_kb_screen_projection));
                            mGlobalVar.setIsManualSetToHDMI(true);
                        }
                        else {
                            mGlobalVar.tranSet_Value(Transfer_Con.HID_CMD_SET_HW_SETTING, 0x00, 0x04);
                            tv_device_button_setting_kb_tvmode_manual_value.setText(getResources().getString(R.string.str_device_button_setting_kb_mobile));
                            mGlobalVar.setIsManualSetToHDMI(false);
                        }
                    }
                    //device_button_setting_kb_tvmode_manual_layout.setEnabled(!isChecked);

                    saveUserData(false);
                }
            });
            iv_device_button_setting_kb_btn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    final android.app.AlertDialog dialog;
                    android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(MainActivity.this);
                    View view = LayoutInflater.from(MainActivity.this).inflate(R.layout.device_button_setting_kb_img_gv_layout, null, false);
                    GridView gv_kb_function_select = view.findViewById(R.id.gv_device_button_setting_kb_img_gv);
                    final List<Map<String, Object>> data_list;
                    SimpleAdapter sim_adapter;
                    data_list = new ArrayList<Map<String, Object>>();
                    TypedArray ar = getResources().obtainTypedArray(R.array.mp1_button_images);
                    int len = ar.length();
                    int[] resIds = new int[len];

                    for(int a=4;a<mGlobalVar.getDirectCenterIndex();a++)
                    {
                        if((a>0x63)&&(a<0x80))
                            continue;
                        if((a==0x88)||(a==0x89))
                            continue;
                        if(mGlobalVar.getIsSupportMultiShotHelp_KB())
                        {
                            if((a>=0x3A)&&(a<=0x3E))
                            {
                                continue;
                            }
                        }
                        Map<String, Object> map = new HashMap<String, Object>();
                        resIds[a] = ar.getResourceId(a, 0);
                        map.put("image", resIds[a]);
                        map.put("id", a);
                        data_list.add(map);
                    }
                    String [] from ={"image"};
                    int [] to = {R.id.iv_kb_gv};
                    sim_adapter = new SimpleAdapter(MainActivity.this, data_list, R.layout.kb_function_select_gv_content, from, to);
                    gv_kb_function_select.setAdapter(sim_adapter);
                    builder.setView(view);
                    builder.setTitle(getResources().getString(R.string.str_global_fast_switch_mouse_and_key_selection));
                    dialog = builder.create();
                    dialog.show();
                    gv_kb_function_select.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                            dialog.dismiss();
                            int group,key;
                            int index = getItemID(data_list,position);
                            TypedArray ar = getResources().obtainTypedArray(R.array.mp1_button_images);
                            iv_device_button_setting_kb_btn.setImageResource(ar.getResourceId(index, 0));
                            ar.recycle();
                            if(index>=0x80)
                            {
                                if(index<0x88)
                                {
                                    group = 0;
                                    key = 1<<(index -0x80);
                                }
                                else
                                {
                                    group = 2;
                                    key = 1<<(index -0x8A);
                                }
                            }
                            else
                            {
                                group = 1;
                                key = index;
                            }

                            if(cb_device_button_setting_kb_switch_to_mouse_press.isChecked())
                            {
                                mGlobalVar.tranSet_Value_retry(Transfer_Con.HID_CMD_SET_MOUSE_SW_KEY, group|0x80, key, 3);
                                mGlobalVar.tranSet_Value_retry(Transfer_Con.HID_CMD_SAVE_DATA, 0x00, 0x00, 1);
                            }
                            else {
                                mGlobalVar.tranSet_Value_retry(Transfer_Con.HID_CMD_SET_MOUSE_SW_KEY, group, key, 3);
                                mGlobalVar.tranSet_Value_retry(Transfer_Con.HID_CMD_SAVE_DATA, 0x00, 0x00, 1);
                            }
                            mGlobalVar.setSwitchToMouseKey_KB((group<<8)|key);
                            bIsSendMouseSwitchToDevice = true;
                            saveUserData(false);
                            //mGlobalVar.saveGameData_KB(mGlobalVar.curPkgName,mGlobalVar.curLabelName,mGlobalVar.coorTbl,mGlobalVar.attrTbl,mGlobalVar.attrEvTbl);
                        }
                    });
                    ar.recycle();
                }
            });
            sb_device_button_setting_kb_rocker_range_value.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
                @Override
                public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                    tv_device_button_setting_kb_rocker_range_value.setText(String.format("%d%%",progress));
                    mGlobalVar.setRockerMoveRange_KB(progress);

                }

                @Override
                public void onStartTrackingTouch(SeekBar seekBar) {

                }

                @Override
                public void onStopTrackingTouch(SeekBar seekBar) {
                    mGlobalVar.tranSet_Value(Transfer_Con.HID_CMD_SET_ROCKER_RANGE,mGlobalVar.getRockerMoveRange_KB(),0);
                    saveUserData(false);
                }
            });

            sw_device_button_setting_kb_force_2touch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    if(isChecked)
                        mGlobalVar.tranSet_Value(Transfer_Con.HID_CMD_SET_HW_SETTING,  0x08, 0x08);
                    else
                        mGlobalVar.tranSet_Value(Transfer_Con.HID_CMD_SET_HW_SETTING,  0x00, 0x08);
                    mGlobalVar.setIsForceViewOut(isChecked);
                    saveUserData(false);
                }
            });

            sw_device_button_setting_kb_virtual_mouse.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    mGlobalVar.setIsUseVirtualMouse(isChecked);
                    saveUserData(false);
                }
            });

            cb_device_button_setting_kb_audio.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    if(isChecked)
                    {
                        mGlobalVar.setIsAudioOut(true);
                    }
                    else
                    {
                        mGlobalVar.setIsAudioOut(false);
                    }
                    saveUserData(false);
                }
            });

            cb_device_button_setting_kb_switch_to_mouse_press.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    if(mGlobalVar.tranGet_Value_retry(Transfer_Con.HID_CMD_GET_MOUSE_SW_KEY,0,0,g_u8DataBuf,5)) {
                        if (isChecked) {
                            g_u8DataBuf[0]=(byte)(g_u8DataBuf[0]|0x80);
                        } else {
                            g_u8DataBuf[0]=(byte)(g_u8DataBuf[0]&0x7F);
                        }
                        mGlobalVar.tranSet_Value_retry(Transfer_Con.HID_CMD_SET_MOUSE_SW_KEY,g_u8DataBuf[0],g_u8DataBuf[4],3);
                        mGlobalVar.tranSet_Value_retry(Transfer_Con.HID_CMD_SAVE_DATA, 0x00, 0x00,1);
                        mGlobalVar.setSwitchToMouseKey_KB(((g_u8DataBuf[0]&0xff)<<8)|(g_u8DataBuf[4]&0xff));
                        bIsSendMouseSwitchToDevice = true;
                        saveUserData(false);
                    }
                }
            });

            sb_device_button_setting_kb_virtual_mouse_speed.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
                @Override
                public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                    tv_device_button_setting_kb_virtual_mouse_speed_value.setText(String.valueOf(progress));
                    mGlobalVar.setVirtualMouseInterval(progress);
                }

                @Override
                public void onStartTrackingTouch(SeekBar seekBar) {

                }

                @Override
                public void onStopTrackingTouch(SeekBar seekBar) {
                    mGlobalVar.tranSet_Value_retry(Transfer_Con.HID_CMD_SET_MOUSE_INTERVAL,  mGlobalVar.getVirtualMouseInterval(), 0x00,3);
                    saveUserData(false);
                }
            });


            device_button_setting_menu_layout= tabGpSetting.findViewById(R.id.device_button_setting_menu_layout);
            device_button_setting_gyro_layout= tabGpSetting.findViewById(R.id.device_button_setting_gyro_layout);
            layout_g_sensor_sense= tabGpSetting.findViewById(R.id.layout_g_sensor_sense);
            device_button_setting_tvmode_layout= tabGpSetting.findViewById(R.id.device_button_setting_tvmode_layout);
            device_button_setting_posswap_layout= tabGpSetting.findViewById(R.id.device_button_setting_posswap_layout);
            device_button_setting_l3r3_layout= tabGpSetting.findViewById(R.id.device_button_setting_l3r3_layout);
            device_button_setting_brake_gas_layout = tabGpSetting.findViewById(R.id.device_button_setting_brake_gas_layout);
            device_button_setting_rocker_setting_swap_layout = tabGpSetting.findViewById(R.id.device_button_setting_rocker_setting_swap_layout);
            device_button_setting_rocker_setting_r_rock_range = tabGpSetting.findViewById(R.id.device_button_setting_rocker_setting_r_rock_range);
            device_button_setting_rocker_setting_sense_layout = tabGpSetting.findViewById(R.id.device_button_setting_rocker_setting_sense_layout);
            device_button_setting_rocker_setting_left_ups = tabGpSetting.findViewById(R.id.device_button_setting_rocker_setting_left_ups);
            device_button_setting_rocker_setting_left_range = tabGpSetting.findViewById(R.id.device_button_setting_rocker_setting_left_range);

            sb_g_sensor_y = tabGpSetting.findViewById(R.id.sb_g_sensor_y);
            sb_g_sensor_x = tabGpSetting.findViewById(R.id.sb_g_sensor_x);
            tv_g_sensor_test_value_y = tabGpSetting.findViewById(R.id.tv_g_sensor_test_value_y);
            tv_g_sensor_test_value_x = tabGpSetting.findViewById(R.id.tv_g_sensor_test_value_x);

            sw_device_button_setting_menu = tabGpSetting.findViewById(R.id.sw_device_button_setting_menu);
            sw_device_button_setting_gyro = tabGpSetting.findViewById(R.id.sw_device_button_setting_gyro);
            sw_device_button_setting_tvmode = tabGpSetting.findViewById(R.id.sw_device_button_setting_tvmode);
            sw_device_button_setting_powswap = tabGpSetting.findViewById(R.id.sw_device_button_setting_powswap);
            rb_device_button_setting_cz = tabGpSetting.findViewById(R.id.rb_device_button_setting_cz);
            rb_device_button_setting_l3r3 = tabGpSetting.findViewById(R.id.rb_device_button_setting_l3r3);
            cb_device_button_setting_brake_gas = tabGpSetting.findViewById(R.id.cb_device_button_setting_brake_gas);

            sb_rocker_setting_min = tabGpSetting.findViewById(R.id.sb_rocker_setting_min);
            sb_rocker_setting_max = tabGpSetting.findViewById(R.id.sb_rocker_setting_max);
            sb_rocker_setting_time = tabGpSetting.findViewById(R.id.sb_rocker_setting_time);
            sb_rocker_setting_left_range = tabGpSetting.findViewById(R.id.sb_rocker_setting_left_range);
            tv_rocker_setting_left_range = tabGpSetting.findViewById(R.id.tv_rocker_setting_left_range);
            tv_rocker_setting_min_value = tabGpSetting.findViewById(R.id.tv_rocker_setting_min_value);
            tv_rocker_setting_max_value = tabGpSetting.findViewById(R.id.tv_rocker_setting_max_value);
            tv_rocker_setting_time_value = tabGpSetting.findViewById(R.id.tv_rocker_setting_time_value);
            iv_rocker_setting_min_del = tabGpSetting.findViewById(R.id.iv_rocker_setting_min_del);
            iv_rocker_setting_min_add = tabGpSetting.findViewById(R.id.iv_rocker_setting_min_add);
            iv_rocker_setting_max_del = tabGpSetting.findViewById(R.id.iv_rocker_setting_max_del);
            iv_rocker_setting_max_add = tabGpSetting.findViewById(R.id.iv_rocker_setting_max_add);
            iv_rocker_setting_time_del = tabGpSetting.findViewById(R.id.iv_rocker_setting_time_del);
            iv_rocker_setting_time_add = tabGpSetting.findViewById(R.id.iv_rocker_setting_time_add);
            ckb_rocker_setting_swap = tabGpSetting.findViewById(R.id.ckb_rocker_setting_swap);
            ckb_rocker_setting_left_ups = tabGpSetting.findViewById(R.id.ckb_rocker_setting_left_ups);
            rb_rocker_setting_r_rocker_range_full = tabGpSetting.findViewById(R.id.rb_rocker_setting_r_rocker_range_full);
            rb_rocker_setting_r_rocker_range_limited = tabGpSetting.findViewById(R.id.rb_rocker_setting_r_rocker_range_limited);

            sb_g_sensor_y.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
                @Override
                public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                    if ((progress == 0) || (progress > 1000))
                        return;
                    int val = (progress << 16) | sb_g_sensor_x.getProgress();
                    if (mGlobalVar.tranSet_Value(Transfer_Con.HID_CMD_WR_RESERVE, 3, val)) {
                        tv_g_sensor_test_value_y.setText(String.valueOf(progress));
                    }
                }

                @Override
                public void onStartTrackingTouch(SeekBar seekBar) {

                }

                @Override
                public void onStopTrackingTouch(SeekBar seekBar) {

                }
            });
            sb_g_sensor_x.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
                @Override
                public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                    if ((progress == 0) || (progress > 1000))
                        return;
                    int val = (sb_g_sensor_y.getProgress() << 16) | progress;
                    if (mGlobalVar.tranSet_Value(Transfer_Con.HID_CMD_WR_RESERVE, 3, val)) {
                        tv_g_sensor_test_value_x.setText(String.valueOf(progress));
                    }
                }

                @Override
                public void onStartTrackingTouch(SeekBar seekBar) {

                }

                @Override
                public void onStopTrackingTouch(SeekBar seekBar) {

                }
            });

            sw_device_button_setting_menu.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    mGlobalVar.tranSet_Value((byte) (Transfer_Con.HID_CMD_SET_HW_SETTING), isChecked ? 0x20 : 0, 0x20);
                }
            });
            sw_device_button_setting_gyro.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    mGlobalVar.tranSet_Value((byte) (Transfer_Con.HID_CMD_SET_HW_SETTING), isChecked ? 0x10 : 0, 0x10);
                }
            });
            sw_device_button_setting_tvmode.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    if (mGlobalVar.tranGet_Value((byte) (Transfer_Con.HID_CMD_RD_RESERVE), 2, 0, g_u8DataBuf)) {
                        int data = (g_u8DataBuf[4] & 0xff) + ((g_u8DataBuf[5] & 0xff) << 8) + ((g_u8DataBuf[6] & 0xff) << 16) + ((g_u8DataBuf[7] & 0xff) << 24);
                        if (isChecked)
                            data |= 0x02;
                        else
                            data &= (~0x02);
                        mGlobalVar.tranSet_Value((byte) (Transfer_Con.HID_CMD_WR_RESERVE), 2, data);
                    }
                }
            });

            sw_device_button_setting_powswap.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    if (mGlobalVar.tranGet_Value((byte) (Transfer_Con.HID_CMD_RD_RESERVE), 2, 0, g_u8DataBuf)) {
                        int data = (g_u8DataBuf[4] & 0xff) + ((g_u8DataBuf[5] & 0xff) << 8) + ((g_u8DataBuf[6] & 0xff) << 16) + ((g_u8DataBuf[7] & 0xff) << 24);
                        if (isChecked)
                            data |= 0x04;
                        else
                            data &= (~0x04);
                        mGlobalVar.tranSet_Value((byte) (Transfer_Con.HID_CMD_WR_RESERVE), 2, data);
                    }
                }
            });

            rb_device_button_setting_cz.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    if (mGlobalVar.tranGet_Value((byte) (Transfer_Con.HID_CMD_RD_RESERVE), 2, 0, g_u8DataBuf)) {
                        int data = (g_u8DataBuf[4] & 0xff) + ((g_u8DataBuf[5] & 0xff) << 8) + ((g_u8DataBuf[6] & 0xff) << 16) + ((g_u8DataBuf[7] & 0xff) << 24);
                        if (isChecked)
                            data &= (~0x01);
                        else
                            data |= 0x01;
                        mGlobalVar.tranSet_Value((byte) (Transfer_Con.HID_CMD_WR_RESERVE), 2, data);
                    }
                }
            });
            rb_device_button_setting_l3r3.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    if (mGlobalVar.tranGet_Value((byte) (Transfer_Con.HID_CMD_RD_RESERVE), 2, 0, g_u8DataBuf)) {
                        int data = (g_u8DataBuf[4] & 0xff) + ((g_u8DataBuf[5] & 0xff) << 8) + ((g_u8DataBuf[6] & 0xff) << 16) + ((g_u8DataBuf[7] & 0xff) << 24);
                        if (isChecked)
                            data |= 0x01;
                        else
                            data &= (~0x01);
                        mGlobalVar.tranSet_Value((byte) (Transfer_Con.HID_CMD_WR_RESERVE), 2, data);
                    }
                }
            });

            cb_device_button_setting_brake_gas.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    if (mGlobalVar.tranGet_Value((byte) (Transfer_Con.HID_CMD_RD_RESERVE), 2, 0, g_u8DataBuf)) {
                        int data = (g_u8DataBuf[4] & 0xff) + ((g_u8DataBuf[5] & 0xff) << 8) + ((g_u8DataBuf[6] & 0xff) << 16) + ((g_u8DataBuf[7] & 0xff) << 24);
                        if (isChecked)
                            data |= 0x08;
                        else
                            data &= (~0x08);
                        mGlobalVar.tranSet_Value((byte) (Transfer_Con.HID_CMD_WR_RESERVE), 2, data);
                    }
                }
            });

            if(Build.VERSION.SDK_INT >= 26)
            {
                sb_rocker_setting_min.setMin(2);
                sb_rocker_setting_max.setMin(20);
                sb_rocker_setting_time.setMin(1);
                sb_rocker_setting_left_range.setMin(1);
            }
            sb_rocker_setting_min.setMax(20);
            sb_rocker_setting_max.setMax(100);
            sb_rocker_setting_time.setMax(60);
            sb_rocker_setting_left_range.setMax(60);


            sb_rocker_setting_min.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
                @Override
                public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                    mGlobalVar.tranSet_Value(Transfer_Con.HID_CMD_SET_R_ROCK_MIN,(progress<1?1:progress),0);
                    tv_rocker_setting_min_value.setText(String.valueOf((progress-2)*100/(sb_rocker_setting_min.getMax()-2))+"%");
                }

                @Override
                public void onStartTrackingTouch(SeekBar seekBar) {

                }

                @Override
                public void onStopTrackingTouch(SeekBar seekBar) {

                }
            });
            sb_rocker_setting_max.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
                @Override
                public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                    mGlobalVar.tranSet_Value(Transfer_Con.HID_CMD_SET_R_ROCK_MAX,(progress<1?1:progress),0);
                    tv_rocker_setting_max_value.setText(String.valueOf((progress-20)*100/(sb_rocker_setting_max.getMax()-20))+"%");
                }

                @Override
                public void onStartTrackingTouch(SeekBar seekBar) {

                }

                @Override
                public void onStopTrackingTouch(SeekBar seekBar) {

                }
            });

            sb_rocker_setting_time.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
                @Override
                public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                    mGlobalVar.tranSet_Value(Transfer_Con.HID_CMD_SET_R_ROCK_TIME,(progress<1?1:progress),0);
                    tv_rocker_setting_time_value.setText(String.valueOf((progress-1)*100/(sb_rocker_setting_time.getMax()-1))+"%");
                }

                @Override
                public void onStartTrackingTouch(SeekBar seekBar) {

                }

                @Override
                public void onStopTrackingTouch(SeekBar seekBar) {

                }
            });

            iv_rocker_setting_min_del.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int data = sb_rocker_setting_min.getProgress();
                    if(Build.VERSION.SDK_INT >= 26) {
                        if (data > sb_rocker_setting_min.getMin()) {
                            data--;
                            sb_rocker_setting_min.setProgress(data);
                        }
                    }
                    else
                    {
                        if (data > 0) {
                            data--;
                            sb_rocker_setting_min.setProgress(data);
                        }
                    }
                }
            });
            iv_rocker_setting_max_del.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int data = sb_rocker_setting_max.getProgress();
                    if(Build.VERSION.SDK_INT >= 26) {
                        if(data>sb_rocker_setting_max.getMin()) {
                            data--;
                            sb_rocker_setting_max.setProgress(data);
                        }
                        else
                        {
                            if (data > 0) {
                                data--;
                                sb_rocker_setting_min.setProgress(data);
                            }
                        }
                    }
                }
            });
            iv_rocker_setting_min_add.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int data = sb_rocker_setting_min.getProgress();
                    if(data<sb_rocker_setting_min.getMax()) {
                        data++;
                        sb_rocker_setting_min.setProgress(data);
                    }
                }
            });
            iv_rocker_setting_max_add.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int data = sb_rocker_setting_max.getProgress();
                    if(data<sb_rocker_setting_max.getMax()) {
                        data++;
                        sb_rocker_setting_max.setProgress(data);
                    }
                }
            });


            iv_rocker_setting_time_del.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int data = sb_rocker_setting_time.getProgress();
                    if(Build.VERSION.SDK_INT >= 26) {
                        if (data > sb_rocker_setting_time.getMin()) {
                            data--;
                            sb_rocker_setting_time.setProgress(data);
                        }
                    }
                    else
                    {
                        if (data > 0) {
                            data--;
                            sb_rocker_setting_time.setProgress(data);
                        }
                    }
                }
            });
            iv_rocker_setting_time_add.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int data = sb_rocker_setting_time.getProgress();
                    if(data<sb_rocker_setting_time.getMax()) {
                        data++;
                        sb_rocker_setting_time.setProgress(data);
                    }
                }
            });



            ckb_rocker_setting_swap.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    if(bIsSwapChecked&&(!isChecked))
                    {
                        if(mGlobalVar.tranSet_Value(Transfer_Con.HID_CMD_SET_HW_SETTING,0x00,0x40))
                        {
                            bIsSwapChecked = false;
                        }
                    }
                    else if(!bIsSwapChecked&&(isChecked))
                    {
                        if(mGlobalVar.tranSet_Value(Transfer_Con.HID_CMD_SET_HW_SETTING,0x40,0x40))
                        {
                            bIsSwapChecked = true;
                        }
                    }
                }
            });

            ckb_rocker_setting_left_ups.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    if(isChecked)
                    {
                        mGlobalVar.tranSet_Value(Transfer_Con.HID_CMD_SET_HW_SETTING,0x02,0x02);
                    }
                    else
                    {
                        mGlobalVar.tranSet_Value(Transfer_Con.HID_CMD_SET_HW_SETTING,0x00,0x02);
                    }
                }
            });

            rb_rocker_setting_r_rocker_range_full.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    if(isChecked)
                        mGlobalVar.tranSet_Value((byte)(Transfer_Con.HID_CMD_SET_HW_SETTING),0,0x08);
                }
            });

            rb_rocker_setting_r_rocker_range_limited.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    if(isChecked)
                        mGlobalVar.tranSet_Value((byte)(Transfer_Con.HID_CMD_SET_HW_SETTING),0x08,0x08);
                }
            });

            sb_rocker_setting_left_range.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
                @Override
                public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                    mGlobalVar.tranSet_Value((byte)(Transfer_Con.HID_CMD_SET_LEFT_VSEN),progress,0);
                    tv_rocker_setting_left_range.setText(String.valueOf(progress*100/sb_rocker_setting_left_range.getMax())+"%");
                }

                @Override
                public void onStartTrackingTouch(SeekBar seekBar) {

                }

                @Override
                public void onStopTrackingTouch(SeekBar seekBar) {

                }
            });

        }
        else {
            tabGpSetting = mInflater.inflate(R.layout.gp_setting_new_layout, null);
            layout_gp_setting_new_phone = tabGpSetting.findViewById(R.id.layout_gp_setting_new_phone);
            layout_gp_setting_new_game = tabGpSetting.findViewById(R.id.layout_gp_setting_new_game);
            layout_gp_setting_image_size = tabGpSetting.findViewById(R.id.layout_gp_setting_image_size);
            layout_gp_setting_new_rocker = tabGpSetting.findViewById(R.id.layout_gp_setting_new_rocker);
            layout_gp_setting_new_reset = tabGpSetting.findViewById(R.id.layout_gp_setting_new_reset);
            layout_gp_setting_new_data = tabGpSetting.findViewById(R.id.layout_gp_setting_new_data);
            layout_gp_setting_new_button = tabGpSetting.findViewById(R.id.layout_gp_setting_new_button);
            layout_gp_setting_new_update = tabGpSetting.findViewById(R.id.layout_gp_setting_new_update);
            layout_gp_setting_new_inject = tabGpSetting.findViewById(R.id.layout_gp_setting_new_inject);
            layout_gp_setting_new_phone.setOnClickListener(onClickListener);
            layout_gp_setting_new_game.setOnClickListener(onClickListener);
            layout_gp_setting_image_size.setOnClickListener(onClickListener);
            layout_gp_setting_new_rocker.setOnClickListener(onClickListener);
            layout_gp_setting_new_reset.setOnClickListener(onClickListener);
            layout_gp_setting_new_data.setOnClickListener(onClickListener);
            layout_gp_setting_new_button.setOnClickListener(onClickListener);
            layout_gp_setting_new_inject.setOnClickListener(onClickListener);
            layout_gp_setting_new_update.setOnClickListener(onClickListener);
        }

        if(Transfer_Con.ENABLE_NEW_USER_INTERFACE)
        {
            tabAppSetting = mInflater.inflate(R.layout.app_setting_new_layout, null);
            layout_app_setting_product = (RelativeLayout) tabAppSetting.findViewById(R.id.layout_app_setting_product);
            layout_app_setting_about = (RelativeLayout) tabAppSetting.findViewById(R.id.layout_app_setting_about);
            layout_app_setting_customer = (RelativeLayout) tabAppSetting.findViewById(R.id.layout_app_setting_customer);
            layout_app_setting_version = (RelativeLayout) tabAppSetting.findViewById(R.id.layout_app_setting_version);
            layout_app_setting_lang = (RelativeLayout) tabAppSetting.findViewById(R.id.layout_app_setting_lang);
            layout_app_setting_status = (RelativeLayout) tabAppSetting.findViewById(R.id.layout_app_setting_status);
            layout_app_setting_new_inject = tabAppSetting.findViewById(R.id.layout_app_setting_new_inject);
            layout_app_setting_new_update = tabAppSetting.findViewById(R.id.layout_app_setting_new_update);
            layout_app_setting_new_reset = tabAppSetting.findViewById(R.id.layout_app_setting_new_reset);
            layout_app_setting_image_size = tabAppSetting.findViewById(R.id.layout_app_setting_image_size);
            layout_app_setting_exit = (RelativeLayout) tabAppSetting.findViewById(R.id.layout_app_setting_exit);

            layout_app_setting_about.setOnClickListener(onClickListener);
            layout_app_setting_version.setOnClickListener(onClickListener);
            layout_app_setting_exit.setOnClickListener(onClickListener);
            layout_app_setting_status.setOnClickListener(onClickListener);
            layout_app_setting_lang.setOnClickListener(onClickListener);
            layout_app_setting_product.setOnClickListener(onClickListener);
            layout_app_setting_new_inject.setOnClickListener(onClickListener);
            layout_app_setting_image_size.setOnClickListener(onClickListener);
            layout_app_setting_new_update.setOnClickListener(onClickListener);
            layout_app_setting_new_reset.setOnClickListener(onClickListener);
            layout_app_setting_customer.setOnClickListener(onClickListener);
        }
        else {
            tabAppSetting = mInflater.inflate(R.layout.app_setting_layout, null);

            layout_app_setting_product = (RelativeLayout) tabAppSetting.findViewById(R.id.layout_app_setting_product);
            layout_app_setting_about = (RelativeLayout) tabAppSetting.findViewById(R.id.layout_app_setting_about);
            layout_app_setting_customer = (RelativeLayout) tabAppSetting.findViewById(R.id.layout_app_setting_customer);
            layout_app_setting_version = (RelativeLayout) tabAppSetting.findViewById(R.id.layout_app_setting_version);
            layout_app_setting_lang = (RelativeLayout) tabAppSetting.findViewById(R.id.layout_app_setting_lang);
            layout_app_setting_status = (RelativeLayout) tabAppSetting.findViewById(R.id.layout_app_setting_status);
            layout_app_setting_exit = (RelativeLayout) tabAppSetting.findViewById(R.id.layout_app_setting_exit);

            layout_app_setting_about.setOnClickListener(onClickListener);
            layout_app_setting_version.setOnClickListener(onClickListener);
            layout_app_setting_exit.setOnClickListener(onClickListener);
            layout_app_setting_status.setOnClickListener(onClickListener);
            layout_app_setting_lang.setOnClickListener(onClickListener);
            layout_app_setting_product.setOnClickListener(onClickListener);
            layout_app_setting_customer.setOnClickListener(onClickListener);
        }
        mViews.add(tabGameList);
        mViews.add(tabGpSetting);
        mViews.add(tabAppSetting);

        device_update_layout = LayoutInflater.from(MainActivity.this).inflate(R.layout.device_update_layout, null, false);
        tv_device_update_version_cur = (TextView)device_update_layout.findViewById(R.id.tv_device_update_version_cur);


        connect_mode_view = LayoutInflater.from(MainActivity.this).inflate(R.layout.connect_mode_layout, null, false);
        iv_connect_mode_cnt_sta = (ImageView) connect_mode_view.findViewById(R.id.iv_connect_mode_cnt_sta);
        tv_connect_mode_cnt_sta = (TextView) connect_mode_view.findViewById(R.id.tv_connect_mode_cnt_sta);

        rb_connect_mode_normal = (RadioButton) connect_mode_view.findViewById(R.id.rb_connect_mode_normal);
        rb_connect_mode_inject = (RadioButton) connect_mode_view.findViewById(R.id.rb_connect_mode_inject);
        rb_connect_mode_gp_normal = (RadioButton) connect_mode_view.findViewById(R.id.rb_connect_mode_gp_normal);
        rb_connect_mode_gp_touch = (RadioButton) connect_mode_view.findViewById(R.id.rb_connect_mode_gp_touch);
        rb_connect_mode_gp_pc = (RadioButton) connect_mode_view.findViewById(R.id.rb_connect_mode_gp_pc_mode);
        rbg_connect_mode_gp_mode = (RadioGroup) connect_mode_view.findViewById(R.id.rbg_connect_mode_gp_mode);

        inject_verify_view = LayoutInflater.from(MainActivity.this).inflate(R.layout.inject_verify_layout,null,false);
        inject_verify_popupWindow= new PopupWindow(inject_verify_view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, true);
        tv_inject_verify_time = (TextView) inject_verify_view.findViewById(R.id.tv_inject_verify_time);

        app_status_info = LayoutInflater.from(MainActivity.this).inflate(R.layout.app_status_info_layout, null, false);
        tv_app_status_info_device_name_content = app_status_info.findViewById(R.id.tv_app_status_info_device_name_content);
        tv_app_status_info_device_ver_content = app_status_info.findViewById(R.id.tv_app_status_info_device_ver_content);
        tv_app_status_info_device_connect_content = app_status_info.findViewById(R.id.tv_app_status_info_device_connect_content);
        tv_app_status_info_device_type_content = app_status_info.findViewById(R.id.tv_app_status_info_device_type_content);
        tv_app_status_info_device_mode_content = app_status_info.findViewById(R.id.tv_app_status_info_device_mode_content);
        app_status_info_device_mode_layout = app_status_info.findViewById(R.id.app_status_info_device_mode_layout);
        mAdapter = new PagerAdapter() {

            @Override
            public void destroyItem(ViewGroup container, int position,
                                    Object object) {
                // TODO Auto-generated method stub
                container.removeView(mViews.get(position));
            }
            @Override
            public Object instantiateItem(ViewGroup container, int position) {
                // TODO Auto-generated method stub
                View view = mViews.get(position);
                container.addView(view);
                return view;
            }
            @Override
            public boolean isViewFromObject(View arg0, Object arg1) {
                // TODO Auto-generated method stub
                return arg0==arg1;
            }
            @Override
            public int getCount() {
                // TODO Auto-generated method stub
                return mViews.size();
            }
        };
        mViewPager.setAdapter(mAdapter);
        getAllDataAndShow();
    }
    private void InitEvent() {
        // TODO Auto-generated method stub
        mGameList.setOnClickListener(this);
        mGamePadSetting.setOnClickListener(this);
        layout_app_setting.setOnClickListener(this);
        //view发生变化
        mViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageSelected(int arg0) {
                // TODO Auto-generated method stub
                int currentItem = mViewPager.getCurrentItem();
                ResetImg();
                switch (currentItem) {
                    case 0:
                        iv_bottom_game.setImageResource(R.drawable.game_sel);
                        tv_bottom_game.setTextColor(getResources().getColor(R.color.titleEndColor));
                        tv_top_title.setText(getResources().getString(R.string.tv_bottom_game_string));
                        break;
                    case 1:
                        iv_bottom_gp_setting.setImageResource(R.drawable.gp_setting_sel);
                        //tv_bottom_gp_setting.setTextColor(Color.rgb(255,120,0));
                        tv_bottom_gp_setting.setTextColor(getResources().getColor(R.color.titleMiddle));
                        tv_top_title.setText(getResources().getString(R.string.tv_bottom_gp_setting_string));
                        if(Transfer_Con.ENABLE_NEW_USER_INTERFACE)
                        {
                            showDeviceButtonSetting_new();
                        }
                        else {
                        if(mGlobalVar.getbIsUsbConnect()) {
                                if (mGlobalVar.getIsCurDeviceKB()) {
                                    layout_gp_setting_new_phone.setVisibility(View.GONE);
                                    layout_gp_setting_new_game.setVisibility(View.GONE);
                                    layout_gp_setting_new_data.setVisibility(View.GONE);
                                    if ((mGlobalVar.getDeviceIndex() == Transfer_Con.DEVICE_MP1_INDEX)) {
                                        if (mGlobalVar.get_IntVersion() >= ((1 << 24) + (1 << 8) + 6))
                                            layout_gp_setting_new_button.setVisibility(View.VISIBLE);
                                        else
                                            layout_gp_setting_new_button.setVisibility(View.GONE);
                                    } else if ((mGlobalVar.getDeviceIndex() == Transfer_Con.DEVICE_BX1_INDEX) || (mGlobalVar.getDeviceIndex() == Transfer_Con.DEVICE_BX2_INDEX)) {
                                        if (mGlobalVar.get_IntVersion() >= ((1 << 24) + (1 << 8) + 4))
                                            layout_gp_setting_new_button.setVisibility(View.VISIBLE);
                                        else
                                            layout_gp_setting_new_button.setVisibility(View.GONE);
                                    } else if ((mGlobalVar.getDeviceIndex() == Transfer_Con.DEVICE_MR1_INDEX) || (mGlobalVar.getDeviceIndex() == Transfer_Con.DEVICE_U41_INDEX)) {
                                        layout_gp_setting_new_button.setVisibility(View.VISIBLE);
                                    } else
                                        layout_gp_setting_new_button.setVisibility(View.GONE);

                                    layout_gp_setting_new_rocker.setVisibility(View.GONE);
                                } else {
                                    if (!Transfer_Con.ENABLE_GAME_DATA_IN_PHONE_GP) {
                                        layout_gp_setting_new_game.setVisibility(View.VISIBLE);
                                        layout_gp_setting_new_phone.setVisibility(View.VISIBLE);
                                        layout_gp_setting_new_data.setVisibility(View.VISIBLE);
                                    }
                                    if (mGlobalVar.getIsSupportMenuKey() && mGlobalVar.getIsSupportMenuKeyOnOff()) {
                                        layout_gp_setting_new_button.setVisibility(View.VISIBLE);
                                        layout_gp_setting_new_rocker.setVisibility(View.VISIBLE);
                                    } else if (mGlobalVar.getDeviceIndex() == Transfer_Con.DEVICE_GM1_INDEX) {
                                        layout_gp_setting_new_button.setVisibility(View.VISIBLE);
                                        layout_gp_setting_new_rocker.setVisibility(View.VISIBLE);
                                    }
                                }
                            }
                        }
                        break;
                    case 2:
                        iv_bottom_app_setting.setImageResource(R.drawable.app_sel);
                        //tv_bottom_app_setting.setTextColor(Color.rgb(255,120,0));
                        tv_bottom_app_setting.setTextColor(getResources().getColor(R.color.titleStartColor));
                        tv_top_title.setText(getResources().getString(R.string.tv_bottom_app_setting_string));
                        break;
                    default:
                        break;
                }
            }

            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {
                // TODO Auto-generated method stub
            }

            @Override
            public void onPageScrollStateChanged(int arg0) {
                // TODO Auto-generated method stub
            }
        });
    }
    private void ResetImg() {
        // TODO Auto-generated method stub

        iv_bottom_game.setImageResource(R.drawable.game_unsel);
        tv_bottom_game.setTextColor(Color.rgb(190,190,190));
        iv_bottom_gp_setting.setImageResource(R.drawable.gp_setting_unsel);
        tv_bottom_gp_setting.setTextColor(Color.rgb(190,190,190));
        iv_bottom_app_setting.setImageResource(R.drawable.app_unsel);
        tv_bottom_app_setting.setTextColor(Color.rgb(190,190,190));
    }

    private void launchCopyCoordinate(String pkgName)
    {
        if(pkgName.contains(Transfer_Con.defPackageName[0]))    //和平精英
        {
            for(int a=0;a<mGlobalVar.getDeviceMaxButton();a++)
            {
                g_u8DataBuf[a*2] = (byte) (Transfer_Con.PT_19p5_9_HPJY[a]&0xff);
                g_u8DataBuf[a*2+1] = (byte) (Transfer_Con.PT_19p5_9_HPJY[a]>>8);
            }
            mGlobalVar.tranSetComboTbl((byte)0,(byte)(mGlobalVar.getDeviceMaxButton()*2),(byte)0,g_u8DataBuf);
            for(int a=0;a<mGlobalVar.getDeviceMaxButton();a++)
            {
                g_u8DataBuf[a*2] = (byte) (Transfer_Con.PT_19p5_9_HPJY[a+mGlobalVar.getDeviceMaxButton()]&0xff);
                g_u8DataBuf[a*2+1] = (byte) (Transfer_Con.PT_19p5_9_HPJY[a+mGlobalVar.getDeviceMaxButton()]>>8);
            }
            mGlobalVar.tranSetComboTbl((byte)0,(byte)(mGlobalVar.getDeviceMaxButton()*2),(byte)1,g_u8DataBuf);
        }
        else if(pkgName.contains(Transfer_Con.defPackageName[1])||pkgName.contains(Transfer_Con.defPackageName[2])) // 王者荣耀
        {
            for(int a=0;a<mGlobalVar.getDeviceMaxButton();a++)
            {
                g_u8DataBuf[a*2] = (byte) (Transfer_Con.PT_19p5_9_WZRY[a]&0xff);
                g_u8DataBuf[a*2+1] = (byte) (Transfer_Con.PT_19p5_9_WZRY[a]>>8);
            }
            mGlobalVar.tranSetComboTbl((byte)0,(byte)(mGlobalVar.getDeviceMaxButton()*2),(byte)0,g_u8DataBuf);
            for(int a=0;a<mGlobalVar.getDeviceMaxButton();a++)
            {
                g_u8DataBuf[a*2] = (byte) (Transfer_Con.PT_19p5_9_WZRY[a+mGlobalVar.getDeviceMaxButton()]&0xff);
                g_u8DataBuf[a*2+1] = (byte) (Transfer_Con.PT_19p5_9_WZRY[a+mGlobalVar.getDeviceMaxButton()]>>8);
            }
            mGlobalVar.tranSetComboTbl((byte)0,(byte)(mGlobalVar.getDeviceMaxButton()*2),(byte)1,g_u8DataBuf);
        }
        else    // User define
        {
            for(int a=0;a<mGlobalVar.getDeviceMaxButton();a++)
            {
                g_u8DataBuf[a*2] = (byte) (Transfer_Con.PT_19p5_9_HPJY[a]&0xff);
                g_u8DataBuf[a*2+1] = (byte) (Transfer_Con.PT_19p5_9_HPJY[a]>>8);
            }
            mGlobalVar.tranSetComboTbl((byte)0,(byte)(mGlobalVar.getDeviceMaxButton()*2),(byte)0,g_u8DataBuf);
            for(int a=0;a<mGlobalVar.getDeviceMaxButton();a++)
            {
                g_u8DataBuf[a*2] = (byte) (Transfer_Con.PT_19p5_9_HPJY[a+mGlobalVar.getDeviceMaxButton()]&0xff);
                g_u8DataBuf[a*2+1] = (byte) (Transfer_Con.PT_19p5_9_HPJY[a+mGlobalVar.getDeviceMaxButton()]>>8);
            }
            mGlobalVar.tranSetComboTbl((byte)0,(byte)(mGlobalVar.getDeviceMaxButton()*2),(byte)1,g_u8DataBuf);
        }
    }
    // Game list page
    class MyAdapter extends BaseAdapter {
        private Context context = null;

        public MyAdapter(Context context) {
            this.context = context;
        }

        @Override
        public int getCount() {
            return dataList.size();
        }

        @Override
        public Object getItem(int position) {
            return dataList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder mHolder;
            final int pos = position;
            if (convertView == null) {
                mHolder = new ViewHolder();
                LayoutInflater inflater = LayoutInflater.from(context);
                //convertView = inflater.inflate(R.layout.listview_layout, null, true);
                convertView = inflater.inflate(R.layout.gridview_layout, null, true);
                //mHolder.tv_lv_id = (TextView) convertView.findViewById(R.id.tv_lv_id);
                mHolder.imageView = (ImageView) convertView.findViewById(R.id.iv_gridview_icon);
                mHolder.textView = (TextView) convertView.findViewById(R.id.tv_gridview_name);
                convertView.setTag(mHolder);
                convertView.setPadding(15, 15, 15, 15);  //每格的间距
            } else {
                mHolder = (ViewHolder) convertView.getTag();
            }

            //mHolder.tv_lv_id.setText(String.valueOf(pos+1));
            //Log.d(TAG,"pos= "+String.valueOf(position));
            //Log.d(TAG,"data= "+dataList.get(position).toString());
            mHolder.imageView.setVisibility(View.VISIBLE);
            if((String)dataList.get(position).get("name")!=null) {
                mHolder.textView.setText((String) dataList.get(position).get("name"));
                mHolder.textView.setSelected(true);
                mHolder.imageView.setImageDrawable((Drawable) dataList.get(position).get("icn"));
            }
            else {
                mHolder.textView.setText("");
                if(mGlobalVar.getIsLastConDeviceKB()) {
                    if (mGlobalVar.getGameListTotalNumKB() == position)
                        mHolder.imageView.setImageResource(R.drawable.add_game);
                    else
                        mHolder.imageView.setVisibility(View.GONE);
                }
                else
                {
                    if (mGlobalVar.getGameListTotalNum() == position)
                        mHolder.imageView.setImageResource(R.drawable.add_game);
                    else
                        mHolder.imageView.setVisibility(View.GONE);
                }
            }
            //if((String)dataList.get(position).get("name")==null)   // 空白位置

            mHolder.imageView.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    if((int)dataList.get(pos).get("type")==Transfer_Con.LIST_TYPE_USER)
                    {
                        View view = LayoutInflater.from(MainActivity.this).inflate(R.layout.pop_del_layout, null, false);
                        LinearLayout layout_pop_enter_sel_del = (LinearLayout) view.findViewById(R.id.layout_pop_enter_sel_del);
                        final PopupWindow popupWindow = new PopupWindow(view, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);

                        popupWindow.setTouchable(true);
                        popupWindow.setTouchInterceptor(new View.OnTouchListener() {
                            @Override
                            public boolean onTouch(View v, MotionEvent event) {
                                return false;
                            }
                        });
                        popupWindow.setBackgroundDrawable(new ColorDrawable(0x00000000));
                        popupWindow.showAsDropDown(v, 50, 0);

                        layout_pop_enter_sel_del.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                popupWindow.dismiss();
                                AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                                builder.setTitle(getResources().getString(R.string.string_pop_reminder))
                                        .setMessage(getResources().getString(R.string.string_pop_reminder_del_confirm))
                                        .setNegativeButton(getResources().getString(R.string.string_pop_cancel), new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialog, int which) {

                                            }
                                        })
                                        .setPositiveButton(getResources().getString(R.string.string_pop_confirm), new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialog, int which) {    //删除
                                                // Game List
                                                dataList.remove(pos);
                                                if (mGlobalVar.getIsLastConDeviceKB()) {
                                                    final int packNamePos = (pos - mGlobalVar.getGameDefExistKB() + Transfer_Con.MAX_GP_FIX_GAME_NUM_KB);
                                                    for (int a = packNamePos; a < mGlobalVar.getUserGameNumKB() + Transfer_Con.MAX_GP_FIX_GAME_NUM_KB - 1; a++) {
                                                        mGlobalVar.setPackageNameKB(a, mGlobalVar.getPackageNameKB(a + 1));
                                                        //Log.d(TAG, "ddddd:" + mGlobalVar.getPackageName(a));
                                                    }
                                                    mGlobalVar.setGameListTotalNumKB(mGlobalVar.getGameListTotalNumKB() - 1);
                                                    for (int a = (pos - mGlobalVar.getGameDefExistKB()); a < mGlobalVar.getUserGameNumKB() - 1; a++) {
                                                        mGlobalVar.setUserGameNameKB(a, mGlobalVar.getUserGameNameKB(a + 1));
                                                    }
                                                    mGlobalVar.setUserGameNumKB(mGlobalVar.getUserGameNumKB() - 1);
                                                    mGlobalVar.setGameGpTotalNumKB(mGlobalVar.getGameGpTotalNumKB() - 1);
                                                } else
                                                {
                                                    // Spinner
                                                    final int packNamePos = (pos - mGlobalVar.getGameDefExist() + Transfer_Con.MAX_GP_FIX_GAME_NUM);
                                                //mGlobalVar.setPackageName(packNamePos,"com.android.opd");
                                                // Current Game Setting
                                                mGlobalVar.tranSet_Value(Transfer_Con.HID_CMD_DEL_GAME, mGlobalVar.getmCurPhone(), packNamePos);
                                                if (mGlobalVar.getmCurGame() >= packNamePos) {
                                                    mGlobalVar.setmCurGame(mGlobalVar.getmCurGame() - 1);
                                                    mGlobalVar.tranSet_Value(Transfer_Con.HID_CMD_SET_GAME_CUR, mGlobalVar.getmCurGame(), 0);
                                                }

                                                for (int a = packNamePos; a < mGlobalVar.getUserGameNum() + Transfer_Con.MAX_GP_FIX_GAME_NUM - 1; a++) {
                                                    mGlobalVar.setPackageName(a, mGlobalVar.getPackageName(a + 1));
                                                    //Log.d(TAG, "ddddd:" + mGlobalVar.getPackageName(a));
                                                }
                                                mGlobalVar.setGameListTotalNum(mGlobalVar.getGameListTotalNum() - 1);
                                                for (int a = (pos - mGlobalVar.getGameDefExist()); a < mGlobalVar.getUserGameNum() - 1; a++) {
                                                    mGlobalVar.setUserGameName(a, mGlobalVar.getUserGameName(a + 1));
                                                }
                                                mGlobalVar.setUserGameNum(mGlobalVar.getUserGameNum() - 1);
                                                mGlobalVar.setGameGpTotalNum(mGlobalVar.getGameGpTotalNum() - 1);

                                            }

                                            if(Transfer_Con.ENABLE_GAME_DATA_IN_PHONE_GP)
                                            {
                                              refreshGameList();
                                            }
                                             else {
                                                Map<String, Object> map = new HashMap<String, Object>();
                                                map.put("id", String.valueOf(0));
                                                //map.put("name", (String) packageInfoList.get(i).packageName);
                                                //map.put("pckname", (String) packageInfoList.get(a).packageName);
                                                map.put("add", R.drawable.plus);
                                                map.put("rev", R.drawable.minus);
                                                map.put("type", Transfer_Con.LIST_TYPE_NULL);
                                                //map.put("start", "Start");
                                                dataList.add(map);
                                                myAdapter.notifyDataSetChanged();
                                                saveUserData(false);
                                                getAllDataAndShow();
                                            }
                                            }
                                        }).create().show();
                            }
                        });
                    }
                    return false;
                }
            });

            mHolder.imageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    if(BuildConfig.DEBUG)
                    {
                        Toast.makeText(MainActivity.this, "工程调试版本，请下载安装正式版本！", Toast.LENGTH_LONG).show();
                    }
                    else
                    {
                        if (!mGlobalVar.getbIsUsbConnect()) {
                            if(mGlobalVar.myUsbDevice==null) {
                                mGlobalVar.enumDevice();
                            }
                            if(mGlobalVar.myUsbDevice!=null) {
                                if (!mGlobalVar.myUsbManager.hasPermission(mGlobalVar.myUsbDevice)) {
                                    requestUSBPermit();
                                    return;
                                }
                                else if(!mGlobalVar.connectDevice())
                                {
                                    if(mGlobalVar.getDeviceIndex()==Transfer_Con.DEVICE_MP1_INDEX)
                                        Toast.makeText(MainActivity.this, getResources().getString(R.string.string_pop_enter_game_not_connect_mnt), Toast.LENGTH_SHORT).show();
                                    else
                                        Toast.makeText(MainActivity.this, getResources().getString(R.string.string_pop_enter_game_not_connect), Toast.LENGTH_SHORT).show();
                                    return;
                                }
                            }
                            else
                                {
                                    Toast.makeText(MainActivity.this, getResources().getString(R.string.string_pop_enter_game_not_connect_device), Toast.LENGTH_SHORT).show();
                                    return;
                                }
                        }
                    }
                    if(((int)dataList.get(pos).get("type")==Transfer_Con.LIST_TYPE_NULL)||((int)dataList.get(pos).get("type")==Transfer_Con.LIST_TYPE_USER_LOST))
                    {    // 增加
                       // Log.d(TAG,"btn_lv_launch");
                        if(Transfer_Con.ENABLE_GAME_DATA_IN_PHONE_GP) {
                            if (mGlobalVar.getUserGameNum() >= (Transfer_Con.MAX_GAME_NUM_IN_PHONE-Transfer_Con.MAX_GP_FIX_GAME_NUM)) {
                                Toast.makeText(MainActivity.this, getResources().getString(R.string.string_pop_add_game_max), Toast.LENGTH_SHORT).show();
                                return;
                            }
                        }
                        else
                        {
                            if (mGlobalVar.getIsCurDeviceGamePad()) {
                                if (mGlobalVar.getUserGameNum() >= 4) {
                                    Toast.makeText(MainActivity.this, getResources().getString(R.string.string_pop_add_game_max), Toast.LENGTH_SHORT).show();
                                    return;
                                }
                            }
                        }
                        final View  view=v;
                        gameList = new ArrayList<Map<String, Object>>();
                        view.setEnabled(false);
                        final PackageManager packageManager = MainActivity.this.getPackageManager();
                        boolean bFlag;
                        List<PackageInfo> packageInfoList = packageManager.getInstalledPackages(PackageManager.MATCH_UNINSTALLED_PACKAGES);
                        if (packageInfoList != null) {
                            for (int i = 0; i < packageInfoList.size(); i++) {
                                //String packName = packageInfoList.get(i).packageName;
                                if((packageInfoList.get(i).applicationInfo.flags& ApplicationInfo.FLAG_SYSTEM)!=0)
                                {
                                    continue;
                                }
                                bFlag = false;

                                if (mGlobalVar.getIsLastConDeviceKB()) {
                                    for (int a = 0; a < mGlobalVar.getGameGpTotalNumKB(); a++) {
                                        if (packageInfoList.get(i).packageName.contains(mGlobalVar.getPackageNameKB(a)))   // 保存列表
                                        {
                                            // double confirm
                                            for (int s = 0; s < dataList.size(); s++) {
                                                String strName = (String) dataList.get(s).get("pckname");
                                                if ((strName != null) && packageInfoList.get(i).packageName.contains(strName)) {
                                                    bFlag = true;
                                                    if (mGlobalVar.getIsLogOn())
                                                        Log.d(TAG, "aaa  " + mGlobalVar.getPackageNameKB(a));
                                                    break;
                                                }
                                            }
                                            if (bFlag)
                                                break;
                                        }
                                    }
                                }
                                else {
                                    for (int a = 0; a < mGlobalVar.getGameGpTotalNum(); a++) {
                                        if (packageInfoList.get(i).packageName.contains(mGlobalVar.getPackageName(a)))   // 保存列表
                                        {
                                            // double confirm
                                            for (int s = 0; s < dataList.size(); s++) {
                                                String strName = (String) dataList.get(s).get("pckname");
                                                if ((strName != null) && packageInfoList.get(i).packageName.contains(strName)) {
                                                    bFlag = true;
                                                    if (mGlobalVar.getIsLogOn())
                                                        Log.d(TAG, "aaa  " + mGlobalVar.getPackageName(a));
                                                    break;
                                                }
                                            }
                                            if (bFlag)
                                                break;
                                        }
                                    }
                                }
                                if(bFlag)
                                    continue;
                                    Map<String, Object> map = new HashMap<String, Object>();
                                    map.put("id", String.valueOf(i + 1));
                                    map.put("icn", packageInfoList.get(i).applicationInfo.loadIcon(getPackageManager()));
                                    map.put("name", packageInfoList.get(i).applicationInfo.loadLabel(getPackageManager()));
                                    //map.put("name", (String) packageInfoList.get(i).packageName);
                                    map.put("pckname", (String) packageInfoList.get(i).packageName);
                                    map.put("start", getResources().getString(R.string.string_pop_game_list_add));
                                    gameList.add(map);
                            }
                            int tempPos,tempGameNum;
                            if (mGlobalVar.getIsLastConDeviceKB())
                            {
                                tempPos = (pos-mGlobalVar.getGameDefExistKB()+Transfer_Con.MAX_GP_FIX_GAME_NUM_KB);
                                tempGameNum = mGlobalVar.getGameListTotalNumKB();
                            }
                            else
                            {
                                tempPos = (pos-mGlobalVar.getGameDefExist()+Transfer_Con.MAX_GP_FIX_GAME_NUM);
                                tempGameNum = mGlobalVar.getGameListTotalNum();
                            }
                            final int packNamePos = tempPos;
                            final int gameNum = tempGameNum;

                            gameListPopupWindow = new GameListPopupWindow(MainActivity.this, gameList,mGlobalVar, (int)dataList.get(pos).get("type"),packNamePos);
                            gameListPopupWindow.showAtLocation(v,
                                    Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);

                            gameListPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener(){
                                @Override
                                public void onDismiss() {
                                    view.setEnabled(true);
                                    //Log.d(TAG,"size="+String.valueOf(gameNum)+" num="+String.valueOf(mGlobalVar.getmGameTotalNum()));
                                    if(mGlobalVar.getIsAddToList())
                                    {
                                        mGlobalVar.setIsAddToList(false);
                                        List<PackageInfo> packageInfoList = packageManager.getInstalledPackages(PackageManager.MATCH_UNINSTALLED_PACKAGES);
                                        if (packageInfoList != null) {
                                            for (int i = 0; i < packageInfoList.size(); i++) {

                                                if((packageInfoList.get(i).applicationInfo.flags& ApplicationInfo.FLAG_SYSTEM)!=0)
                                                {
                                                    continue;
                                                }
                                                String packName = packageInfoList.get(i).packageName;
                                                String tempPackageName;
                                                if (mGlobalVar.getIsLastConDeviceKB())
                                                {
                                                    tempPackageName =mGlobalVar.getPackageNameKB(mGlobalVar.getGameGpTotalNumKB() - 1);
                                                }
                                                else
                                                {
                                                    tempPackageName =mGlobalVar.getPackageName(mGlobalVar.getGameGpTotalNum() - 1);
                                                }
                                                if (packName.equals(tempPackageName)) {
                                                    Map<String, Object> map = new HashMap<String, Object>();
                                                    map.put("id", String.valueOf(i + 1));
                                                    map.put("icn", packageInfoList.get(i).applicationInfo.loadIcon(getPackageManager()));
                                                    map.put("name", packageInfoList.get(i).applicationInfo.loadLabel(getPackageManager()));
                                                    //Log.d(TAG, (String) packageInfoList.get(i).applicationInfo.loadLabel(getPackageManager()));
                                                    //map.put("name", (String) packageInfoList.get(i).packageName);
                                                    map.put("pckname", (String) packageInfoList.get(i).packageName);
                                                    map.put("add", R.drawable.plus);
                                                    map.put("rev", R.drawable.minus);
                                                    map.put("type", Transfer_Con.LIST_TYPE_USER);
                                                    map.put("start", getResources().getString(R.string.string_pop_game_list_enter));
                                                    dataList.remove(gameNum);
                                                    dataList.add(gameNum,map);
                                                    if (mGlobalVar.getIsLastConDeviceKB()) {
                                                        mGlobalVar.setUserGameNameKB(mGlobalVar.getUserGameNumKB(),(String) packageInfoList.get(i).applicationInfo.loadLabel(getPackageManager()));
                                                        mGlobalVar.setUserGameNumKB(mGlobalVar.getUserGameNumKB()+1);
                                                    }
                                                    else
                                                    {
                                                        mGlobalVar.setUserGameName(mGlobalVar.getUserGameNum(),(String) packageInfoList.get(i).applicationInfo.loadLabel(getPackageManager()));
                                                        mGlobalVar.setUserGameNum(mGlobalVar.getUserGameNum()+1);
                                                    }

                                                    myAdapter.notifyDataSetChanged();
                                                    saveUserData(true);
                                                    AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                                                    builder.setTitle(getResources().getString(R.string.string_pop_reminder))
                                                            .setMessage(getResources().getString(R.string.string_pop_reminder_new_game))
                                                            .setPositiveButton(getResources().getString(R.string.string_pop_reminder_new_game_to_set), new DialogInterface.OnClickListener() {
                                                                @Override
                                                                public void onClick(DialogInterface dialog, int which) {
                                                                    if (mGlobalVar.getIsLastConDeviceKB())
                                                                    {
                                                                        mGlobalVar.curPkgName = (String)dataList.get(pos).get("pckname");
                                                                        mGlobalVar.curLabelName = (String)dataList.get(pos).get("name");
                                                                        if(mRes_Hei>mRes_Wid) {
                                                                            int retry = 5;
                                                                            while(retry>0) {
                                                                                if(mGlobalVar.tranSet_Value(Transfer_Con.HID_CMD_SET_SCREEN_RESOLUTION, mRes_Hei, mRes_Wid))
                                                                                    break;
                                                                                retry--;
                                                                            }
                                                                        }
                                                                        else {
                                                                            int retry = 5;
                                                                            while (retry > 0) {
                                                                                if (mGlobalVar.tranSet_Value(Transfer_Con.HID_CMD_SET_SCREEN_RESOLUTION, mRes_Wid, mRes_Hei))
                                                                                    break;
                                                                                retry--;
                                                                            }
                                                                        }

                                                                        if(!mGlobalVar.loadGameData_KB(mGlobalVar.curPkgName,mGlobalVar.curLabelName,mGlobalVar.coorTbl,mGlobalVar.attrTbl,mGlobalVar.attrEvTbl))
                                                                        {
                                                                            mGlobalVar.setDefaultGameData_KB(mGlobalVar.curPkgName,mGlobalVar.coorTbl,mGlobalVar.attrTbl,mGlobalVar.attrEvTbl);
                                                                            mGlobalVar.saveGameData_KB(mGlobalVar.curPkgName,mGlobalVar.curLabelName,mGlobalVar.coorTbl,mGlobalVar.attrTbl,mGlobalVar.attrEvTbl);

                                                                                mGlobalVar.tranSet_Value(Transfer_Con.HID_CMD_SET_R_ROCK_MIN, mGlobalVar.localSetting_KB[0], 0);
                                                                                if (mGlobalVar.getIsSupportMouseSideKeyAndHorSense()) {
                                                                                    mGlobalVar.tranSet_Value(Transfer_Con.HID_CMD_SET_R_ROCK_MAX, mGlobalVar.localSetting_KB[1], 0);
                                                                                    if(!bIsSendMouseSwitchToDevice) {
                                                                                        mGlobalVar.tranSet_Value(Transfer_Con.HID_CMD_SET_MOUSE_SW_KEY, mGlobalVar.localSetting_KB[2], mGlobalVar.localSetting_KB[3]);
                                                                                        bIsSendMouseSwitchToDevice = true;
                                                                                        saveUserData(false);
                                                                                    }
                                                                            }
                                                                        }
                                                                        else
                                                                        {
                                                                            if(mGlobalVar.tranGet_Value_retry(Transfer_Con.HID_CMD_GET_MOUSE_SW_KEY,0,0,g_u8DataBuf,5))
                                                                            {
                                                                                mGlobalVar.setSwitchToMouseKey_KB(((g_u8DataBuf[0]&0xff)<<8)|(g_u8DataBuf[4]&0xff));
                                                                            }
                                                                        }
                                                                        mGlobalVar.sendCoordinateToDevice_KB();
                                                                        mGlobalVar.sendAttributeToDevice_KB();
                                                                        mGlobalVar.sendAttributeEventTableToDevice_KB();
                                                                        mGlobalVar.sendLocalSettingToDevice();
                                                                        startLocalApp(mGlobalVar.curPkgName);
                                                                        {
                                                                            Intent intent = new Intent(MainActivity.this, FloatMenuService_New.class);
                                                                            startService(intent);
                                                                        }
                                                                    }
                                                                    else {
                                                                        if(Transfer_Con.ENABLE_GAME_DATA_IN_PHONE_GP)
                                                                        {
                                                                            mGlobalVar.curPkgName = (String)dataList.get(pos).get("pckname");
                                                                            mGlobalVar.curLabelName = (String)dataList.get(pos).get("name");

                                                                            if(mRes_Hei>mRes_Wid) {
                                                                                int retry = 5;
                                                                                while(retry>0) {
                                                                                    if(mGlobalVar.tranSet_Value(Transfer_Con.HID_CMD_SET_SCREEN_RESOLUTION, mRes_Hei, mRes_Wid))
                                                                                        break;
                                                                                    retry--;
                                                                                }
                                                                            }
                                                                            else {
                                                                                int retry = 5;
                                                                                while (retry > 0) {
                                                                                    if (mGlobalVar.tranSet_Value(Transfer_Con.HID_CMD_SET_SCREEN_RESOLUTION, mRes_Wid, mRes_Hei))
                                                                                        break;
                                                                                    retry--;
                                                                                }
                                                                            }

                                                                            if(!mGlobalVar.loadGameData_GP(mGlobalVar.curPkgName,mGlobalVar.curLabelName,mGlobalVar.coorTbl,mGlobalVar.attrTbl,mGlobalVar.attrEvTbl))
                                                                            {
                                                                                mGlobalVar.setDefaultGameData_GP(mGlobalVar.curPkgName,mGlobalVar.coorTbl,mGlobalVar.attrTbl,mGlobalVar.attrEvTbl);
                                                                                mGlobalVar.saveGameData_GP(mGlobalVar.curPkgName,mGlobalVar.curLabelName,mGlobalVar.coorTbl,mGlobalVar.attrTbl,mGlobalVar.attrEvTbl);
                                                                            }

                                                                            mGlobalVar.sendCoordinateToDevice_GP(false);
                                                                            mGlobalVar.sendAttributeToDevice_GP(false);
                                                                            mGlobalVar.sendAttributeEventTableToDevice_GP(false);
                                                                            startLocalApp(mGlobalVar.curPkgName);
                                                                            {
                                                                                Intent intent = new Intent(MainActivity.this, FloatMenuService.class);
                                                                                startService(intent);
                                                                            }
                                                                        }
                                                                        else {
                                                                            mGlobalVar.tranSet_Value(Transfer_Con.HID_CMD_SET_GAME_CUR, Transfer_Con.MAX_GP_FIX_GAME_NUM + mGlobalVar.getUserGameNum() - 1, 0);
                                                                            mGlobalVar.setmCurGame(Transfer_Con.MAX_GP_FIX_GAME_NUM + mGlobalVar.getUserGameNum() - 1);
                                                                            if (bIsGPNormalMode)
                                                                                Toast.makeText(MainActivity.this, getResources().getString(R.string.string_pop_gamepad_mode_simulator), Toast.LENGTH_LONG).show();
                                                                            viewPostion();
                                                                        }
                                                                    }
                                                                }
                                                            })
                                                            .setNegativeButton(getResources().getString(R.string.string_pop_reminder_new_game_later), new DialogInterface.OnClickListener() {
                                                                @Override
                                                                public void onClick(DialogInterface dialog, int which) {
                                                                    refreshGameList();
                                                                }
                                                            }).create().show();
                                                }
                                            }
                                        }
                                        //Log.d(TAG,mGlobalVar.getPackageName(mGlobalVar.getmGameTotalNum() - 1));
                                    }
                                }
                            });
                        }
                    } else {    // Start Game
                        if(bIsGPNormalMode)
                            Toast.makeText(MainActivity.this,getResources().getString(R.string.string_pop_gamepad_mode_simulator),Toast.LENGTH_LONG).show();
                        /*
                        if(mGlobalVar.getDeviceIndex()==Transfer_Con.DEVICE_HN2_INDEX)
                        {
                            launchCopyCoordinate((String)dataList.get(pos).get("pckname"));
                            startLocalApp((String) dataList.get(pos).get("pckname"));
                            //if (!mGlobalVar.getIsFloatServiceRunning())
                            {
                                Intent intent = new Intent(MainActivity.this, FloatMenuService_New.class);
                                startService(intent);
                            }
                        }
                        else*/
                        if(mGlobalVar.getIsCurDeviceKB())
                        {
                            mGlobalVar.curPkgName = (String)dataList.get(pos).get("pckname");
                            mGlobalVar.curLabelName = (String)dataList.get(pos).get("name");
                            if(mRes_Hei>mRes_Wid) {
                                int retry = 5;
                                while(retry>0) {
                                    if(mGlobalVar.tranSet_Value(Transfer_Con.HID_CMD_SET_SCREEN_RESOLUTION, mRes_Hei, mRes_Wid))
                                        break;
                                    retry--;
                                }
                            }
                            else {
                                int retry = 5;
                                while (retry > 0) {
                                    if (mGlobalVar.tranSet_Value(Transfer_Con.HID_CMD_SET_SCREEN_RESOLUTION, mRes_Wid, mRes_Hei))
                                        break;
                                    retry--;
                                }
                            }

                            if(!mGlobalVar.loadGameData_KB(mGlobalVar.curPkgName,mGlobalVar.curLabelName,mGlobalVar.coorTbl,mGlobalVar.attrTbl,mGlobalVar.attrEvTbl))
                            {
                                mGlobalVar.setDefaultGameData_KB(mGlobalVar.curPkgName,mGlobalVar.coorTbl,mGlobalVar.attrTbl,mGlobalVar.attrEvTbl);
                                mGlobalVar.tranSet_Value(Transfer_Con.HID_CMD_SET_R_ROCK_MIN,mGlobalVar.localSetting_KB[0],0);
                                mGlobalVar.saveGameData_KB(mGlobalVar.curPkgName,mGlobalVar.curLabelName,mGlobalVar.coorTbl,mGlobalVar.attrTbl,mGlobalVar.attrEvTbl);
                                if(mGlobalVar.getIsSupportMouseSideKeyAndHorSense())
                                {
                                    mGlobalVar.tranSet_Value(Transfer_Con.HID_CMD_SET_R_ROCK_MAX,mGlobalVar.localSetting_KB[1],0);
                                    mGlobalVar.tranSet_Value(Transfer_Con.HID_CMD_SET_MOUSE_SW_KEY,mGlobalVar.localSetting_KB[2],mGlobalVar.localSetting_KB[3]);
                                }
                            }
                            else
                            {
                                if(mGlobalVar.tranGet_Value_retry(Transfer_Con.HID_CMD_GET_MOUSE_SW_KEY,0,0,g_u8DataBuf,5))
                                {
                                    mGlobalVar.setSwitchToMouseKey_KB(((g_u8DataBuf[0]&0xff)<<8)|(g_u8DataBuf[4]&0xff));
                                }
                            }
                            //Log.d(TAG,"----------------------------------"+String.valueOf(mGlobalVar.localSetting_KB[0]));
                            mGlobalVar.sendCoordinateToDevice_KB();
                            mGlobalVar.sendAttributeToDevice_KB();
                            mGlobalVar.sendAttributeEventTableToDevice_KB();
                            mGlobalVar.sendLocalSettingToDevice();
                            startLocalApp(mGlobalVar.curPkgName);
                            {
                                Intent intent = new Intent(MainActivity.this, FloatMenuService_New.class);
                                startService(intent);
                            }

                        }
                        else {

                            if(Transfer_Con.ENABLE_GAME_DATA_IN_PHONE_GP)
                            {
                                mGlobalVar.curPkgName = (String)dataList.get(pos).get("pckname");
                                mGlobalVar.curLabelName = (String)dataList.get(pos).get("name");

                                if(mRes_Hei>mRes_Wid) {
                                    int retry = 5;
                                    while(retry>0) {
                                        if(mGlobalVar.tranSet_Value(Transfer_Con.HID_CMD_SET_SCREEN_RESOLUTION, mRes_Hei, mRes_Wid))
                                            break;
                                        retry--;
                                    }
                                }
                                else {
                                    int retry = 5;
                                    while (retry > 0) {
                                        if (mGlobalVar.tranSet_Value(Transfer_Con.HID_CMD_SET_SCREEN_RESOLUTION, mRes_Wid, mRes_Hei))
                                            break;
                                        retry--;
                                    }
                                }

                                if(!mGlobalVar.loadGameData_GP(mGlobalVar.curPkgName,mGlobalVar.curLabelName,mGlobalVar.coorTbl,mGlobalVar.attrTbl,mGlobalVar.attrEvTbl))
                                {
                                    mGlobalVar.setDefaultGameData_GP(mGlobalVar.curPkgName,mGlobalVar.coorTbl,mGlobalVar.attrTbl,mGlobalVar.attrEvTbl);
                                }

                                mGlobalVar.sendCoordinateToDevice_GP(false);
                                mGlobalVar.sendAttributeToDevice_GP(false);
                                mGlobalVar.sendAttributeEventTableToDevice_GP(false);
                                startLocalApp(mGlobalVar.curPkgName);
                                {
                                    Intent intent = new Intent(MainActivity.this, FloatMenuService.class);
                                    startService(intent);
                                }

                            }
                            else {
                                if (mGlobalVar.get_CurGame(g_u8DataBuf)) {
                                    mGlobalVar.setmCurGame(g_u8DataBuf[0]);
                                }

                                if (!gameCompare((String) dataList.get(pos).get("pckname"), pos, (String) dataList.get(pos).get("name"))) {
                                    mGlobalVar.setmCurGame(getGameIndex((String) dataList.get(pos).get("pckname"), (String) dataList.get(pos).get("name")));
                                    mGlobalVar.tranSet_Value(Transfer_Con.HID_CMD_SET_GAME_CUR, mGlobalVar.getmCurGame(), 0);
                                }
                                if(mRes_Hei>mRes_Wid) {
                                    int retry = 5;
                                    while(retry>0) {
                                        if(mGlobalVar.tranSet_Value(Transfer_Con.HID_CMD_SET_SCREEN_RESOLUTION, mRes_Hei, mRes_Wid))
                                            break;
                                        retry--;
                                    }
                                }
                                else {
                                    int retry = 5;
                                    while (retry > 0) {
                                        if (mGlobalVar.tranSet_Value(Transfer_Con.HID_CMD_SET_SCREEN_RESOLUTION, mRes_Wid, mRes_Hei))
                                            break;
                                        retry--;
                                    }
                                }
                                mGlobalVar.getCurCorTbl();
                            /*
                            if(mGlobalVar.getDeviceIndex()==Transfer_Con.DEVICE_GM1_INDEX) {
                                if (((String) ((String) dataList.get(pos).get("pckname"))).contains(Transfer_Con.defPackageName[0]) || ((String) ((String) dataList.get(pos).get("pckname"))).contains(Transfer_Con.defPackageName[4]) || ((String) ((String) dataList.get(pos).get("pckname"))).contains(Transfer_Con.defPackageName[5])
                                        || ((String) ((String) dataList.get(pos).get("pckname"))).contains(Transfer_Con.defPackageName[6]) || ((String) ((String) dataList.get(pos).get("pckname"))).contains(Transfer_Con.defPackageName[7]) || ((String) ((String) dataList.get(pos).get("pckname"))).contains(Transfer_Con.defPackageName[8])
                                        || ((String) ((String) dataList.get(pos).get("pckname"))).contains(Transfer_Con.defPackageName[9])) {
                                    mGlobalVar.tranSet_Value((byte)(Transfer_Con.HID_CMD_SET_HW_SETTING),0x10,0x10);
                                } else {

                                    mGlobalVar.tranSet_Value((byte)(Transfer_Con.HID_CMD_SET_HW_SETTING),0,0x10);
                                }
                            }
                             */
                                startLocalApp((String) dataList.get(pos).get("pckname"));
                                if (!mGlobalVar.getIsFloatServiceRunning()) {
                                    Intent intent = new Intent(MainActivity.this, FloatMenuService.class);
                                    startService(intent);
                                }
                            }
                        }
                        // launch game
                        /*
                        {
                            View view = LayoutInflater.from(MainActivity.this).inflate(R.layout.pop_enter_sel_layout, null, false);
                            LinearLayout layout_pop_enter_sel_left = (LinearLayout) view.findViewById(R.id.layout_pop_enter_sel_left);
                            LinearLayout layout_pop_enter_sel_right = (LinearLayout) view.findViewById(R.id.layout_pop_enter_sel_right);
                            LinearLayout layout_pop_enter_sel_del = (LinearLayout) view.findViewById(R.id.layout_pop_enter_sel_del);
                            if(pos<Transfer_Con.MAX_GP_FIX_GAME_NUM)
                                layout_pop_enter_sel_del.setVisibility(View.GONE);
                            final PopupWindow popupWindow = new PopupWindow(view, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);

                            popupWindow.setTouchable(true);
                            popupWindow.setTouchInterceptor(new View.OnTouchListener() {
                                @Override
                                public boolean onTouch(View v, MotionEvent event) {
                                    return false;
                                }
                            });
                            popupWindow.setBackgroundDrawable(new ColorDrawable(0x00000000));
                            popupWindow.showAsDropDown(v, 50, 0);

                            layout_pop_enter_sel_left.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    popupWindow.dismiss();
                                    if (!gameCompare((String) dataList.get(pos).get("pckname"), pos,(String) dataList.get(pos).get("name"))) {
                                        mGlobalVar.setmCurGame(getGameIndex((String) dataList.get(pos).get("pckname"),(String) dataList.get(pos).get("name")));
                                        mGlobalVar.tranSet_Value(Transfer_Con.HID_CMD_SET_GAME_CUR, mGlobalVar.getmCurGame(), 0);
                                    }
                                    //mGlobalVar.setIsAdvSetNeedGuide(true);
                                    //viewPostion();
                                    startLocalApp((String) dataList.get(pos).get("pckname"));
                                    Intent intent = new Intent(MainActivity.this, FloatMenuService.class);
                                    startService(intent);
                                }
                            });
                            layout_pop_enter_sel_right.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    popupWindow.dismiss();
                                    if (!gameCompare((String) dataList.get(pos).get("pckname"), pos,(String) dataList.get(pos).get("name"))) {
                                        mGlobalVar.setmCurGame(getGameIndex((String) dataList.get(pos).get("pckname"),(String) dataList.get(pos).get("name")));
                                        mGlobalVar.tranSet_Value(Transfer_Con.HID_CMD_SET_GAME_CUR, mGlobalVar.getmCurGame(), 0);
                                    }
                                    //mGlobalVar.setIsEnterGameNeedGuide(true);
                                    startLocalAppPermit((String) dataList.get(pos).get("pckname"));
                                }
                            });
                            layout_pop_enter_sel_del.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    popupWindow.dismiss();
                                    AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                                    builder.setTitle("温馨提示")
                                            .setMessage("该操作将会删除手机以及手柄里面保存的该游戏相关数据，请确认是否继续。“确认”将继续删除，“取消”会取消操作")
                                            .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                                @Override
                                                public void onClick(DialogInterface dialog, int which) {

                                                }
                                            })
                                            .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                                                @Override
                                                public void onClick(DialogInterface dialog, int which) {
                                                    // Game List
                                                    dataList.remove(pos);
                                                    // Spinner
                                                    final int packNamePos = (pos-mGlobalVar.getGameDefExist()+Transfer_Con.MAX_GP_FIX_GAME_NUM);
                                                    mGlobalVar.setPackageName(packNamePos,"com.android.opd");
                                                    // Current Game Setting
                                                    mGlobalVar.tranSet_Value(Transfer_Con.HID_CMD_DEL_GAME,mGlobalVar.getmCurPhone(),packNamePos);
                                                    if(mGlobalVar.getmCurGame()>=packNamePos)
                                                    {
                                                        mGlobalVar.setmCurGame(mGlobalVar.getmCurGame()-1);
                                                        mGlobalVar.tranSet_Value(Transfer_Con.HID_CMD_SET_GAME_CUR,mGlobalVar.getmCurGame(),0);

                                                    }
                                                    Map<String, Object> map = new HashMap<String, Object>();
                                                    map.put("id", String.valueOf(0));
                                                    //map.put("name", (String) packageInfoList.get(i).packageName);
                                                    //map.put("pckname", (String) packageInfoList.get(a).packageName);
                                                    map.put("add", R.drawable.plus);
                                                    map.put("rev", R.drawable.minus);
                                                    map.put("type", Transfer_Con.LIST_TYPE_NULL);
                                                    //map.put("start", "Start");
                                                    dataList.add(map);
                                                    mGlobalVar.setGameListTotalNum(mGlobalVar.getGameListTotalNum()-1);
                                                    for(int a=(pos-mGlobalVar.getGameDefExist());a<mGlobalVar.getUserGameNum()-1;a++)
                                                    {
                                                        mGlobalVar.setUserGameName(a,mGlobalVar.getUserGameName(a+1));
                                                    }
                                                    mGlobalVar.setUserGameNum(mGlobalVar.getUserGameNum()-1);
                                                    mGlobalVar.setGameGpTotalNum(mGlobalVar.getGameGpTotalNum() - 1);
                                                    myAdapter.notifyDataSetChanged();
                                                    saveUserData();
                                                    getAllDataAndShow();
                                                }
                                            }).create().show();
                                }
                            });
                        }
                        */
                    }
                }
            });
            return convertView;
        }

        class ViewHolder {
            ImageView imageView;
            TextView textView;
        }
    }

    class ItemSelAdapter extends  BaseAdapter{
        Context context;
        ArrayList<Map<String, Object>> data;
        public ItemSelAdapter(Context context,ArrayList<Map<String, Object>> data) {
            this.context = context;
            this.data = data;
        }
        @Override
        public int getCount() {
            return data.size();
        }

        @Override
        public Object getItem(int position) {
            return data.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            ViewHolder viewHolder;
            final int pos = position;
            if (convertView == null) {
                viewHolder = new ViewHolder();
                LayoutInflater inflater = LayoutInflater.from(context);
                convertView = inflater.inflate(R.layout.listview_item_rb_sel_layout, null, true);
                //mHolder.tv_lv_id = (TextView) convertView.findViewById(R.id.tv_lv_id);
                viewHolder.radioButton = (RadioButton) convertView.findViewById(R.id.rb_listview_item_sel);
                viewHolder.textView = (TextView) convertView.findViewById(R.id.tv_listview_item_sel);
                convertView.setTag(viewHolder);
                convertView.setPadding(15, 15, 15, 15);  //每格的间距
            } else {
                viewHolder = (ViewHolder) convertView.getTag();
            }

            viewHolder.textView.setText((String)data.get(position).get("text"));
            viewHolder.radioButton.setChecked((boolean)data.get(position).get("val"));


            //Log.d(TAG,"ssss  "+String.valueOf(position)+" "+String.valueOf((boolean)data.get(position).get("val")));
            return convertView;
        }

        class ViewHolder
        {
            TextView textView;
            RadioButton radioButton;
        }
    }

    public void sendInjectModeSetting(boolean val)
    {
        if(mGlobalVar.getIsCurDeviceGamePad()) {
            byte[] data = new byte[2];
            data[0] = 0x13;
            if (val) {
                data[1] = 1;
            } else {
                data[1] = 0;
            }
            udpSocketHelper.sendCmd(data, 2);
        }
    }

    public void sendSimulateMode()
    {
        if(mGlobalVar.getIsCurDeviceGamePad()) {
            byte[] data = new byte[2];
            data[0] = 0x15;
            if (mGlobalVar.getIsSimulateMode()) {
                data[1] = 1;
            } else {
                data[1] = 0;
            }
            udpSocketHelper.sendCmd(data, 2);
        }
    }

    public void sendConnectStatus(boolean val,boolean showProcessBar)
    {
        if(mGlobalVar.getIsCurDeviceGamePad()) {
            byte[] data = new byte[2];
            data[0] = 0x10;
            if (val) {
                data[1] = 1;
            } else {
                data[1] = 0;
            }
            udpSocketHelper.sendCmd(data,2);
        }
        //Log.d(TAG,"sendConnectStatus");

        mGlobalVar.setIsInjectServerRunning(false);
        mGlobalVar.setIsInjectMode(false);
        Message msg = new Message();
        if(showProcessBar)
            msg.what = TO_GET_SERVER_STATUS;
        else
            msg.what = UPDATE_SERVER_STATUS;
        launchHandler.sendMessageDelayed(msg, 1000);//设置在SPLASHTIME时间后，发送消息

    }

    public void sendConnectStatus1(boolean val)
    {
        if(mGlobalVar.getIsCurDeviceGamePad()) {
            byte[] data = new byte[2];
            data[0] = 0x10;
            if (val) {
                data[1] = 1;
            } else {
                data[1] = 0;
            }
            //Log.d(TAG,"sendConnectStatus");
            udpSocketHelper.sendCmd(data, 2);
        }
    }

    public void getInjectStatus()
    {
        if(mGlobalVar.getIsCurDeviceGamePad()) {
            byte[] data = new byte[2];
            data[0] = 0x12;
            data[1] = 1;
            udpSocketHelper.sendCmd(data, 2);
        }
        Message msg = new Message();
        msg.what = UPDATE_SERVER_STATUS;
        launchHandler.sendMessageDelayed(msg, 1000);//设置在SPLASHTIME时间后，发送消息
    }

    public void getSimulateStatus()
    {
        if(mGlobalVar.getIsCurDeviceGamePad()) {
            byte[] data = new byte[2];
            data[0] = 0x14;
            data[1] = 1;
            udpSocketHelper.sendCmd(data, 2);
        }
    }

    private final BroadcastReceiver mUsbPermissionActionReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();

            if (ACTION_USB_PERMISSION.equals(action)) {
                synchronized (this) {
                    UsbDevice usbDevice = (UsbDevice)intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
                    if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
                        //user choose YES for your previously popup window asking for grant perssion for this usb device
                        if(null != usbDevice){
                            if(!mGlobalVar.getbIsUsbConnect())
                            {
                                if(mGlobalVar.connectDevice())
                                {
                                    if(mGlobalVar.getIsCurDeviceKB())//(mGlobalVar.getDeviceIndex()==Transfer_Con.DEVICE_MP1_INDEX)||(mGlobalVar.getDeviceIndex()==Transfer_Con.DEVICE_BX1_INDEX)||(mGlobalVar.getDeviceIndex()==Transfer_Con.DEVICE_BX2_INDEX)||(mGlobalVar.getDeviceIndex()==Transfer_Con.DEVICE_MR1_INDEX)||(mGlobalVar.getDeviceIndex()==Transfer_Con.DEVICE_U41_INDEX))
                                    {
                                        if (mGlobalVar.tranGet_Value(Transfer_Con.HID_CMD_GET_HW_SETTING, 0, 0xFF, g_u8DataBuf))
                                        {
                                            if((g_u8DataBuf[0]&0x01)==0x01)
                                            {
                                                tv_app_status_info_device_type_content.setText(getResources().getString(R.string.string_app_status_info_office_mode));
                                            }
                                            else
                                            {
                                                tv_app_status_info_device_type_content.setText(getResources().getString(R.string.string_app_status_info_game_mode));
                                            }
                                        }
                                    }
                                    else if(mGlobalVar.getDeviceIndex()==Transfer_Con.DEVICE_GM1_INDEX)
                                    {
                                        if (mGlobalVar.tranGet_Value(Transfer_Con.HID_CMD_GET_HW_SETTING, 0, 0x84, g_u8DataBuf)) {
                                            if ((g_u8DataBuf[0] & 0x80) == 0x80) {
                                                if((g_u8DataBuf[0] & 0x04) == 0x04) {
                                                    mGlobalVar.setIsPC360Mode(true);
                                                    mGlobalVar.setIsSimulateMode(true);
                                                }
                                                else {
                                                    mGlobalVar.setIsSimulateMode(true);
                                                    mGlobalVar.setIsPC360Mode(false);
                                                }
                                            } else {
                                                mGlobalVar.setIsSimulateMode(false);
                                                mGlobalVar.setIsPC360Mode(false);
                                            }
                                        }
                                    }
                                    else {
                                        mGlobalVar.setIsPC360Mode(false);
                                        if (mGlobalVar.tranGet_Value(Transfer_Con.HID_CMD_GET_HW_SETTING, 0, mGlobalVar.getIsSupportMenuKey() ? 0x80 : 0, g_u8DataBuf)) {
                                            if ((g_u8DataBuf[0] & 0x80) == 0x80) {
                                                mGlobalVar.setIsSimulateMode(true);
                                                bIsGPNormalMode = true;
                                            } else {
                                                mGlobalVar.setIsSimulateMode(false);
                                                bIsGPNormalMode = false;
                                            }
                                        }
                                    }
                                    //sendSimulateMode();
                                    launchLayout.setVisibility(View.GONE);
                                    iv_top_connect.setImageResource(R.drawable.connect);
                                    getAllDataAndShow();
                                    if(mGlobalVar.getIsCurDeviceGamePad())
                                        sendSimulateMode();
                                    try {
                                        Thread.sleep(100);
                                    } catch (InterruptedException e) {
                                        e.printStackTrace();
                                    }
                                    sendConnectStatus(true,true);
                                    //getInjectStatus();
                                }
                            }
                        }
                    }
                    else {
                        //user choose NO for your previously popup window asking for grant perssion for this usb device
                        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                        builder.setTitle(getResources().getString(R.string.string_pop_permitted_request))
                                .setMessage(getResources().getString(R.string.string_pop_permitted_request_content))
                                .setPositiveButton(getResources().getString(R.string.string_pop_permitted_request_request_again), new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        requestUSBPermit();
                                    }
                                })
                                .setNegativeButton(getResources().getString(R.string.string_pop_reminder_new_game_later), new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {

                                    }
                                }).create().show();

                    }
                }
            }
        }
    };


    void requestUSBPermit()
    {
        IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
        registerReceiver(mUsbPermissionActionReceiver, filter);
        g_bIsRegisterUsbPermitRec =  true;
        PendingIntent mPermissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0);
        mGlobalVar.myUsbManager.requestPermission(mGlobalVar.myUsbDevice, mPermissionIntent);
    }

    void autoPermitRequest()
    {
        // Float
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (!Settings.canDrawOverlays(MainActivity.this)) {

                AlertDialog.Builder builder= new AlertDialog.Builder(MainActivity.this);
                builder.setTitle(getResources().getString(R.string.string_pop_permitted_request))
                        .setMessage(getResources().getString(R.string.string_pop_permitted_request_content1))
                        .setPositiveButton(getResources().getString(R.string.string_pop_permitted_request_request), new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);
                                Uri packageURI = Uri.parse("package:" + getPackageName());
                                intent.setData(packageURI);
                                startActivity(intent);
                            }
                        })
                        .setNegativeButton(getResources().getString(R.string.string_pop_reminder_new_game_later), new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                Toast.makeText(MainActivity.this, getResources().getString(R.string.string_pop_float_permitted_tip), Toast.LENGTH_SHORT).show();
                            }
                        }).create().show();

            }
        }
        // Write & Read
        if (Build.VERSION.SDK_INT >= 26 && checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.ACCESS_FINE_LOCATION}, 2);
        }
        // USB
        if(mGlobalVar.myUsbDevice!=null) {
            if (!mGlobalVar.myUsbManager.hasPermission(mGlobalVar.myUsbDevice)) {
                requestUSBPermit();
            }
        }
    }

    private void startLocalAppPermit(String packageNameTarget) {
        if (Settings.canDrawOverlays(MainActivity.this)) {
            startLocalApp(packageNameTarget);
            if(!mGlobalVar.getIsGameServiceRunning()) {
                Intent intent = new Intent(MainActivity.this, EnterGameService.class);
                startService(intent);
            }
            finish();
        } else {
            //若没有权限，提示获取.
            if(bIs1stGetOverFloatPermit) {
                bIs1stGetOverFloatPermit = false;
                saveUserData(false);
                Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);
                //if (Build.VERSION.SDK_INT != Build.VERSION_CODES.O)
                {
                    Uri packageURI = Uri.parse("package:" + getPackageName());
                    intent.setData(packageURI);
                }
                Toast.makeText(MainActivity.this, getResources().getString(R.string.string_pop_float_permitted_tip), Toast.LENGTH_SHORT).show();
                startActivity(intent);
            }
            else {
                startLocalApp(packageNameTarget);
                Toast.makeText(MainActivity.this, getResources().getString(R.string.string_pop_float_permitted_tip), Toast.LENGTH_SHORT).show();
                finish();
            }
        }
    }

    private void startLocalApp(String packageNameTarget) {
        if (appIsExist(packageNameTarget)) {
            PackageManager packageManager = getPackageManager();
            Intent intent = packageManager.getLaunchIntentForPackage(packageNameTarget);
            startActivity(intent);
        } else {
            Toast.makeText(getApplicationContext(), getResources().getString(R.string.string_pop_game_list_not_install), Toast.LENGTH_SHORT).show();
        }
    }

    private boolean appIsExist(String packageNameTarget) {
        PackageManager packageManager = getPackageManager();
        List<PackageInfo> packageInfoList = packageManager.getInstalledPackages(PackageManager.MATCH_UNINSTALLED_PACKAGES);
        for (PackageInfo packageInfo : packageInfoList) {
            String packageNameSource = packageInfo.packageName;
            if (packageNameSource.equals(packageNameTarget)) {
                return true;
            }
        }
        return false;
    }


    // Status page
    // USB Transfer
    /*
    private boolean assignEndpoint() {
        if (mGlobalVar.myInterface.getEndpoint(1) != null) {
            mGlobalVar.setUsbEpOut(mGlobalVar.myInterface.getEndpoint(1));
        } else {
            mGlobalVar.setbIsUsbConnect(false);
            return false;
        }
        if (mGlobalVar.myInterface.getEndpoint(0) != null) {
            mGlobalVar.setUsbEpIn(mGlobalVar.myInterface.getEndpoint(0));
        } else {
            mGlobalVar.setbIsUsbConnect(false);
            return false;
        }
        mGlobalVar.setbIsUsbConnect(true);
        Log.d(TAG,"assignEndpoint");
        return true;
    }
    private boolean openDevice() {
        if (mGlobalVar.myInterface != null) {
            UsbDeviceConnection conn = null;
            if (mGlobalVar.myUsbManager.hasPermission(mGlobalVar.myUsbDevice)) {
                conn = mGlobalVar.myUsbManager.openDevice(mGlobalVar.myUsbDevice);
            }
            else
            {
                Toast.makeText(this,"No Permission",Toast.LENGTH_SHORT).show();
            }
            if (conn == null) {
                return false;
            }

            if (conn.claimInterface(mGlobalVar.myInterface, true)) {
                //DeviceConnection = conn; // 到此你的android设备已经连上HID设备
                mGlobalVar.setDeviceConnection(conn);
                return true;
            } else {
                conn.close();
            }
        }
        return false;
    }
    private boolean findInterface() {
        if (mGlobalVar.myUsbDevice != null) {
            for (int i = 0; i < mGlobalVar.myUsbDevice.getInterfaceCount(); i++) {
                UsbInterface intf = mGlobalVar.myUsbDevice.getInterface(i);
                if (intf.getInterfaceClass() == INTERFACE_CLASS
                        && intf.getInterfaceSubclass() == INTERFACE_SUBCLASS
                        && intf.getInterfaceProtocol() == INTERFACE_PROTOCOL) {
                    mGlobalVar.myInterface = intf;
                    return true;
                }
            }
        }
        return false;
    }
    private int enumDevice() {
        if (mGlobalVar.myUsbManager == null)
            return -1;
        HashMap<String, UsbDevice> deviceList = mGlobalVar.myUsbManager.getDeviceList();
        if (!deviceList.isEmpty()) {
            StringBuffer sb = new StringBuffer();
            for (UsbDevice device : deviceList.values()) {
                sb.append(device.toString());
                sb.append("\n");
                // 枚举到设备
                if (device.getVendorId() == Transfer_Con.VendorID){

                    if(device.getProductId() == ISPCmd_Con.ProductID) {
                        //bisUsbTranMode = false;
                        mGlobalVar.setbIsTransferMode(false);
                        Toast.makeText(this,"ISP Connect",Toast.LENGTH_SHORT).show();
                    }
                    else if(device.getProductId() ==Transfer_Con.ProductID)
                    {
                        //bisUsbTranMode = true;
                        mGlobalVar.setbIsTransferMode(true);
                        Toast.makeText(this,"Transfer Connect",Toast.LENGTH_SHORT).show();
                    }
                    mGlobalVar.myUsbDevice = device;
                    return 1;
                }
            }
        }
        return 0;
    }
    private boolean connectDevice()
    {
        if(mGlobalVar.getbIsUsbConnect())
            return true;
        if (enumDevice() > 0) {
            if (findInterface()) {
                if (openDevice())
                {
                    if (assignEndpoint())
                    {
                        if(!mGlobalVar.getbIsTransferMode()) {

                        }
                        return true;
                    }
                }
            }
        }
        return false;
    }
    */
    public  View.OnClickListener onClickListener = new View.OnClickListener()
    {

        @Override
        public void onClick(View v) {
            switch (v.getId())
            {
                case R.id.layout_gp_setting_new_phone:
                    showPhoneSelPopWin();
                    break;
                case R.id.layout_gp_setting_new_game:
                    showGameSelPopWin();
                    break;
                case R.id.layout_gp_setting_image_size:
                case R.id.layout_app_setting_image_size:
                    showIconSetting();
                    break;
                case R.id.layout_gp_setting_new_rocker:
                    if(!BuildConfig.DEBUG) {
                        if (!mGlobalVar.getbIsUsbConnect()) {
                            Toast.makeText(MainActivity.this, getResources().getString(R.string.string_pop_enter_game_not_connect), Toast.LENGTH_SHORT).show();
                            return;
                        }
                    }
                    showRockerSetting();
                    break;
                case R.id.layout_gp_setting_new_button:
                    if(!BuildConfig.DEBUG) {
                        if (!mGlobalVar.getbIsUsbConnect()) {
                            Toast.makeText(MainActivity.this, getResources().getString(R.string.string_pop_enter_game_not_connect), Toast.LENGTH_SHORT).show();
                            return;
                        }
                    }
                    showDeviceButtonSetting();
                    break;
                case R.id.layout_app_setting_new_reset:
                case R.id.layout_gp_setting_new_reset: {
                    if(!BuildConfig.DEBUG) {
                        if (!mGlobalVar.getbIsUsbConnect()) {
                            Toast.makeText(MainActivity.this, getResources().getString(R.string.string_pop_enter_game_not_connect), Toast.LENGTH_SHORT).show();
                            return;
                        }
                    }

                    if(mGlobalVar.getIsLastConDeviceKB()) {
                        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                        builder.setTitle(getResources().getString(R.string.string_pop_reminder_restore_confirm))
                                .setMessage(getResources().getString(R.string.string_pop_reminder_restore_data_confirm_content))
                                .setPositiveButton(getResources().getString(R.string.string_pop_confirm), new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        mGlobalVar.tranSet_Value(Transfer_Con.HID_CMD_DATA_RESET,1,0);
                                        mGlobalVar.clearGameData_KB();
                                        Intent intent2 = new Intent(MainActivity.this, FloatMenuService_New.class);
                                        stopService(intent2);
                                        bIsSendMouseSwitchToDevice = false;
                                    }
                                })
                                .setNegativeButton(getResources().getString(R.string.string_pop_cancel), new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {

                                    }
                                }).create().show();
                    }
                    else {
                        if(Transfer_Con.ENABLE_GAME_DATA_IN_PHONE_GP)
                        {
                            AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                            builder.setTitle(getResources().getString(R.string.string_pop_reminder_restore_confirm))
                                    .setMessage(getResources().getString(R.string.string_pop_reminder_restore_data_confirm_content))
                                    .setPositiveButton(getResources().getString(R.string.string_pop_confirm), new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            mGlobalVar.clearGameData_KB();
                                            Intent intent2 = new Intent(MainActivity.this, FloatMenuService.class);
                                            stopService(intent2);
                                            if (mGlobalVar.tranSet_Value((byte) (Transfer_Con.HID_CMD_DATA_RESET), 1, 0)) {
                                                //mGlobalVar.setGameGpTotalNum(Transfer_Con.MAX_GP_DEF_GAME_NUM);
                                                //mGlobalVar.setUserGameNum(0);
                                                getAllDataAndShow();
                                                saveUserData(false);
                                            }
                                        }
                                    })
                                    .setNegativeButton(getResources().getString(R.string.string_pop_cancel), new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {

                                        }
                                    }).create().show();
                        }
                        else {
                            AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                            builder.setTitle(getResources().getString(R.string.string_pop_reminder_restore_confirm))
                                    .setMessage(getResources().getString(R.string.string_pop_reminder_restore_confirm_content))
                                    .setPositiveButton(getResources().getString(R.string.string_pop_confirm), new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            if (mGlobalVar.tranSet_Value((byte) (Transfer_Con.HID_CMD_DATA_RESET), 1, 0)) {
                                                //mGlobalVar.setGameGpTotalNum(Transfer_Con.MAX_GP_DEF_GAME_NUM);
                                                //mGlobalVar.setUserGameNum(0);
                                                getAllDataAndShow();
                                                saveUserData(false);
                                            }
                                        }
                                    })
                                    .setNegativeButton(getResources().getString(R.string.string_pop_cancel), new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {

                                        }
                                    }).create().show();
                        }
                    }
                }
                    break;
                case R.id.layout_gp_setting_new_data:
                    if(!BuildConfig.DEBUG) {
                        if (!mGlobalVar.getbIsUsbConnect()) {
                            Toast.makeText(MainActivity.this, getResources().getString(R.string.string_pop_enter_game_not_connect), Toast.LENGTH_SHORT).show();
                            return;
                        }
                    }
                    showDataSetting();
                    break;
                case R.id.layout_app_setting_version:
                    showAppVersion();
                    break;
                case R.id.layout_app_setting_new_update:
                case R.id.layout_gp_setting_new_update:
                    showDeviceUpdate();
                    //
                    break;
                case R.id.layout_app_setting_new_inject:
                case R.id.layout_gp_setting_new_inject:
                    showConnectMode();
                    break;


                case R.id.layout_app_setting_about:
                    showAppSettingAbout();
                    break;
                case R.id.layout_app_setting_product:
                    showAppSettingProduct();
                    break;
                case R.id.layout_app_setting_customer:
                    showAppCustomer();
                    break;
                case R.id.layout_app_setting_lang:
                    showAppLanguage();
                    break;
                case R.id.layout_app_setting_status:
                    showAppStatusInfo();
                    break;
                case R.id.layout_app_setting_exit: {
                    AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                    builder.setTitle(getResources().getString(R.string.string_pop_reminder_exit_confirm))
                            .setPositiveButton(getResources().getString(R.string.string_pop_confirm), new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    finish();
                                }
                            })
                            .setNegativeButton(getResources().getString(R.string.string_pop_cancel), new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {

                                }
                            }).create().show();
                }
                    break;
            }
        }
    };

    void showPhoneSelPopWin()
    {
        View view = LayoutInflater.from(MainActivity.this).inflate(R.layout.pop_phone_sel_layout,null,false);


        Button btn_pop_phone_sel_back = (Button)view.findViewById(R.id.btn_pop_phone_sel_back);
        TextView tv_pop_phone_sel_current = (TextView)view.findViewById(R.id.tv_pop_phone_sel_current);
        ListView lv_pop_phone_sel = (ListView)view.findViewById(R.id.lv_pop_phone_sel);
        ArrayList<Map<String, Object>> data =  new ArrayList<Map<String, Object>>();
        if(mGlobalVar.get_CurPhone(g_u8DataBuf))
        {
            mGlobalVar.setmCurPhone(g_u8DataBuf[0]);
        }
        for(int a=0;a<Transfer_Con.MAX_PHONE_NUM;a++)
        {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("text", Transfer_Con.Str_Res[a]);
            map.put("val", (mGlobalVar.getmCurPhone()==a));
            data.add(map);
        }
        ItemSelAdapter itemSelAdapter = new ItemSelAdapter(MainActivity.this,data);
        lv_pop_phone_sel.setAdapter(itemSelAdapter);

        int r = mRes_Wid / 9;
        float h = (float) mRes_Hei/r;

        String str = getResources().getString(R.string.string_pop_phone_sel_current);
        if((mRes_Hei%r)==0)
            str =str+String.format("%dx%d,"+getResources().getString(R.string.string_pop_phone_sel_ratio)+"%.0f:%d。",mRes_Hei,mRes_Wid,h,9);
        else if(((mRes_Hei*10)%r)==0)
            str =str+String.format("%dx%d,"+getResources().getString(R.string.string_pop_phone_sel_ratio)+"%.01f:%d。",mRes_Hei,mRes_Wid,h,9);
        else
            str =str+String.format("%dx%d,"+getResources().getString(R.string.string_pop_phone_sel_ratio)+"%.02f:%d。",mRes_Hei,mRes_Wid,h,9);
        tv_pop_phone_sel_current.setText(str);

        final PopupWindow popupWindow = new PopupWindow(view,ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.MATCH_PARENT,true);

        popupWindow.setTouchable(true);
        popupWindow.setTouchInterceptor(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return false;
            }
        });
        popupWindow.setBackgroundDrawable(new ColorDrawable(0xFFF8F8F8));
        //popupWindow.showAsDropDown(v);  //showAsDropDown(v,50,0);
        popupWindow.showAtLocation(view,Gravity.CENTER|Gravity.BOTTOM,0,0);
        btn_pop_phone_sel_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });
        lv_pop_phone_sel.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //Toast.makeText(MainActivity.this,"Item click "+String.valueOf(position),Toast.LENGTH_SHORT).show();
                if(!BuildConfig.DEBUG) {
                    if (!mGlobalVar.getbIsUsbConnect()) {
                        Toast.makeText(MainActivity.this, getResources().getString(R.string.string_pop_enter_game_not_connect), Toast.LENGTH_SHORT).show();
                        return;
                    }
                }

                if(position!=mGlobalVar.getmCurPhone())
                {
                    if(mGlobalVar.tranSet_Value(Transfer_Con.HID_CMD_SET_PHONE_CUR,position,0))
                    {
                        mGlobalVar.setmCurPhone(position);
                        //tv_setting_new_phone_cur.setText(Transfer_Con.Str_Res[position]);
                        //Toast.makeText(MainActivity.this,"Item click "+String.valueOf(position),Toast.LENGTH_SHORT).show();
                    }
                }
                popupWindow.dismiss();
            }
        });
    }
    void showGameSelPopWin()
    {
        View view = LayoutInflater.from(MainActivity.this).inflate(R.layout.pop_game_sel_layout,null,false);
        Button button = (Button)view.findViewById(R.id.btn_pop_game_sel_back);
        ListView listView = (ListView)view.findViewById(R.id.lv_pop_game_sel);
        ArrayList<Map<String, Object>> data =  new ArrayList<Map<String, Object>>();

        //
        if(mGlobalVar.get_CurGame(g_u8DataBuf))
        {
            mGlobalVar.setmCurGame(g_u8DataBuf[0]);
        }

        for(int a=0;a<mGlobalVar.getGameGpTotalNum();a++)
        {
            Map<String, Object> map = new HashMap<String, Object>();
            if(a<Transfer_Con.MAX_GP_FIX_GAME_NUM)
                map.put("text", Transfer_Con.GameName[a]);
            else
                map.put("text", mGlobalVar.getUserGameName(a-Transfer_Con.MAX_GP_FIX_GAME_NUM));
            map.put("val", (mGlobalVar.getmCurGame()==a));
            data.add(map);
        }
        ItemSelAdapter itemSelAdapter = new ItemSelAdapter(MainActivity.this,data);
        listView.setAdapter(itemSelAdapter);
        final PopupWindow popupWindow = new PopupWindow(view,ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.WRAP_CONTENT,true);

        popupWindow.setTouchable(true);
        popupWindow.setTouchInterceptor(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return false;
            }
        });
        popupWindow.setBackgroundDrawable(new ColorDrawable(0xFFF8F8F8));
        //popupWindow.showAsDropDown(v);  //showAsDropDown(v,50,0);
        popupWindow.showAtLocation(view,Gravity.CENTER|Gravity.BOTTOM,0,0);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //Toast.makeText(MainActivity.this,"Item click "+String.valueOf(position),Toast.LENGTH_SHORT).show();
                if(!BuildConfig.DEBUG) {
                    if (!mGlobalVar.getbIsUsbConnect()) {
                        Toast.makeText(MainActivity.this, getResources().getString(R.string.string_pop_enter_game_not_connect), Toast.LENGTH_SHORT).show();
                        return;
                    }
                }

               // Log.d(TAG,"gameindex ="+String.valueOf(position));

                if(position!=mGlobalVar.getmCurGame())
                {
                    if(mGlobalVar.tranSet_Value(Transfer_Con.HID_CMD_SET_GAME_CUR,position,0))
                    {
                        mGlobalVar.setmCurGame(position);
                        //if(mGlobalVar.getmCurGame()<Transfer_Con.MAX_GP_FIX_GAME_NUM)
                         //   tv_setting_new_game_cur.setText(Transfer_Con.GameName[mGlobalVar.getmCurGame()]);
                        //else
                         //   tv_setting_new_game_cur.setText(mGlobalVar.getUserGameName(mGlobalVar.getmCurGame()-Transfer_Con.MAX_GP_FIX_GAME_NUM));
                    }
                }
                popupWindow.dismiss();
            }
        });
    }


    boolean checkAppValid()
    {
        File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+LOCAL_PATH+NAME_UPDATE_APK);
        if(file.exists())
        {
            if(file.length()==mGlobalVar.mAppSize) {
                update();
                file.delete();
                return true;
            }
            else
            {
                file.delete();

                return false;
            }
        }
        else
        {
            return false;
        }

    }

    void checkAppUpdate()
    {
        if(bIsAppCanUpdate)
        {
            if (Build.VERSION.SDK_INT >= 26 && checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                    != PackageManager.PERMISSION_GRANTED) {
                requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
            } else {
                if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {

                    if(checkAppValid())
                        return;
                }
            }
            if(NetStatusUtils.getNetWorkStates(MainActivity.this)==NetStatusUtils.TYPE_NONE)
            {
                AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                builder.setTitle(getResources().getString(R.string.string_pop_reminder_network_error))
                        .setMessage(getResources().getString(R.string.string_pop_reminder_network_error_content))
                        .setPositiveButton(getResources().getString(R.string.string_pop_confirm), new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                            }
                        }).create().show();

            }
            else if((NetStatusUtils.getNetWorkStates(MainActivity.this)==NetStatusUtils.TYPE_MOBILE)) {
                AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                builder.setTitle(getResources().getString(R.string.string_pop_reminder))
                        .setMessage(getResources().getString(R.string.string_pop_reminder_network_mobile))
                        .setPositiveButton(getResources().getString(R.string.string_pop_continue), new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                downFile(app_info.strUrl, "update");
                            }
                        })
                        .setNegativeButton(getResources().getString(R.string.string_pop_cancel), new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                            }
                        })
                        .create().show();
            }
            else
            {
                downFile(app_info.strUrl, "update");
            }
        }
        else {
            getServerVersionCode();
        }
    }

    void showFAQDetail(int item)
    {
        String strTitle="",strContent="";
        View view = LayoutInflater.from(MainActivity.this).inflate(R.layout.faq_detail_layout,null,false);
        ImageView button = (ImageView)view.findViewById(R.id.iv_faq_detail_back);
        TextView tv_faq_detail_question = (TextView)view.findViewById(R.id.tv_faq_detail_question);
        TextView tv_faq_detail_answer = (TextView)view.findViewById(R.id.tv_faq_detail_answer);
        switch (item)
        {
            case 1:
                strTitle =getResources().getString(R.string.str_faq_question_item_1);
                strContent=getResources().getString(R.string.str_faq_answer_item_1);
                break;
            case 2:
                strTitle =getResources().getString(R.string.str_faq_question_item_2);
                strContent=getResources().getString(R.string.str_faq_answer_item_2);
                break;
            case 3:
                strTitle =getResources().getString(R.string.str_faq_question_item_3);
                strContent=getResources().getString(R.string.str_faq_answer_item_3);
                break;
            case 4:
                strTitle =getResources().getString(R.string.str_faq_question_item_4);
                strContent=getResources().getString(R.string.str_faq_answer_item_4);
                break;
            case 5:
                strTitle =getResources().getString(R.string.str_faq_question_item_5);
                strContent=getResources().getString(R.string.str_faq_answer_item_5);
                break;
            case 6:
                strTitle =getResources().getString(R.string.str_faq_question_item_6);
                strContent=getResources().getString(R.string.str_faq_answer_item_6);
                break;
            case 7:
                strTitle =getResources().getString(R.string.str_faq_question_item_7);
                strContent=getResources().getString(R.string.str_faq_answer_item_7);
                break;
            case 8:
                strTitle =getResources().getString(R.string.str_faq_question_item_8);
                strContent=getResources().getString(R.string.str_faq_answer_item_8);
                break;
            case 9:
                strTitle =getResources().getString(R.string.str_faq_question_item_9);
                strContent=getResources().getString(R.string.str_faq_answer_item_9);
                break;
            case 10:
                strTitle =getResources().getString(R.string.str_faq_question_item_10);
                strContent=getResources().getString(R.string.str_faq_answer_item_10);
                break;
        }
        tv_faq_detail_question.setText(strTitle);
        tv_faq_detail_answer.setText(strContent);
        final PopupWindow popupWindow = new PopupWindow(view,ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.MATCH_PARENT,true);
        popupWindow.setTouchable(true);
        popupWindow.setTouchInterceptor(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return false;
            }
        });
        popupWindow.setBackgroundDrawable(new ColorDrawable(0xFFF8F8F8));
        //popupWindow.showAsDropDown(v);  //showAsDropDown(v,50,0);
        popupWindow.showAtLocation(view,Gravity.CENTER|Gravity.BOTTOM,0,0);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });
    }

    View.OnClickListener faqOnClickListener= new View.OnClickListener()// ()
    {
        @Override
        public void onClick(View v) {
            byte index =1;
            switch(v.getId())
            {
                case R.id.layout_app_custom_server_item1:
                    index =1;
                    break;
                case R.id.layout_app_custom_server_item2:
                    index =2;
                    break;
                case R.id.layout_app_custom_server_item3:
                    index =3;
                    break;
                case R.id.layout_app_custom_server_item4:
                    index =4;
                    break;
                case R.id.layout_app_custom_server_item5:
                    index =5;
                    break;
                case R.id.layout_app_custom_server_item6:
                    index =6;
                    break;
                case R.id.layout_app_custom_server_item7:
                    index =7;
                    break;
                case R.id.layout_app_custom_server_item8:
                    index =8;
                    break;
                case R.id.layout_app_custom_server_item9:
                    index =9;
                    break;
                case R.id.layout_app_custom_server_item10:
                    index =10;
                    break;
            }
            showFAQDetail(index);
        }
    };

    void showAppCustomer()
    {
        View view = LayoutInflater.from(MainActivity.this).inflate(R.layout.app_custom_server_layout,null,false);
        ImageView button = (ImageView)view.findViewById(R.id.iv_app_custom_server_back);
        ImageView iv_app_custom_server_service = (ImageView)view.findViewById(R.id.iv_app_custom_server_service);
        TextView  tv_app_custom_server_item1 = (TextView)view.findViewById(R.id.tv_app_custom_server_item1);
        TextView  tv_app_custom_server_item2 = (TextView)view.findViewById(R.id.tv_app_custom_server_item2);
        TextView  tv_app_custom_server_item3 = (TextView)view.findViewById(R.id.tv_app_custom_server_item3);
        TextView  tv_app_custom_server_item4 = (TextView)view.findViewById(R.id.tv_app_custom_server_item4);
        TextView  tv_app_custom_server_item5 = (TextView)view.findViewById(R.id.tv_app_custom_server_item5);
        TextView  tv_app_custom_server_item6 = (TextView)view.findViewById(R.id.tv_app_custom_server_item6);
        TextView  tv_app_custom_server_item7 = (TextView)view.findViewById(R.id.tv_app_custom_server_item7);
        TextView  tv_app_custom_server_item8 = (TextView)view.findViewById(R.id.tv_app_custom_server_item8);
        TextView  tv_app_custom_server_item9 = (TextView)view.findViewById(R.id.tv_app_custom_server_item9);
        TextView  tv_app_custom_server_item10 = (TextView)view.findViewById(R.id.tv_app_custom_server_item10);

        RelativeLayout layout_app_custom_server_item1 = (RelativeLayout)view.findViewById(R.id.layout_app_custom_server_item1);
        RelativeLayout layout_app_custom_server_item2 = (RelativeLayout)view.findViewById(R.id.layout_app_custom_server_item2);
        RelativeLayout layout_app_custom_server_item3 = (RelativeLayout)view.findViewById(R.id.layout_app_custom_server_item3);
        RelativeLayout layout_app_custom_server_item4 = (RelativeLayout)view.findViewById(R.id.layout_app_custom_server_item4);
        RelativeLayout layout_app_custom_server_item5 = (RelativeLayout)view.findViewById(R.id.layout_app_custom_server_item5);
        RelativeLayout layout_app_custom_server_item6 = (RelativeLayout)view.findViewById(R.id.layout_app_custom_server_item6);
        RelativeLayout layout_app_custom_server_item7 = (RelativeLayout)view.findViewById(R.id.layout_app_custom_server_item7);
        RelativeLayout layout_app_custom_server_item8 = (RelativeLayout)view.findViewById(R.id.layout_app_custom_server_item8);
        RelativeLayout layout_app_custom_server_item9 = (RelativeLayout)view.findViewById(R.id.layout_app_custom_server_item9);
        RelativeLayout layout_app_custom_server_item10 = (RelativeLayout)view.findViewById(R.id.layout_app_custom_server_item10);
        /*
        tv_app_custom_server_item1.setSelected(true);
        tv_app_custom_server_item2.setSelected(true);
        tv_app_custom_server_item3.setSelected(true);
        tv_app_custom_server_item4.setSelected(true);
        tv_app_custom_server_item5.setSelected(true);
        tv_app_custom_server_item6.setSelected(true);
        tv_app_custom_server_item7.setSelected(true);
        tv_app_custom_server_item8.setSelected(true);
        tv_app_custom_server_item9.setSelected(true);
        tv_app_custom_server_item10.setSelected(true);
        */
        final PopupWindow popupWindow = new PopupWindow(view,ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.MATCH_PARENT,true);
        popupWindow.setTouchable(true);
        popupWindow.setTouchInterceptor(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return false;
            }
        });
        popupWindow.setBackgroundDrawable(new ColorDrawable(0xFFF8F8F8));
        //popupWindow.showAsDropDown(v);  //showAsDropDown(v,50,0);
        popupWindow.showAtLocation(view,Gravity.CENTER|Gravity.BOTTOM,0,0);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });
        iv_app_custom_server_service.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(MainActivity.this,getResources().getString(R.string.string_pop_customer_service_coming),Toast.LENGTH_SHORT).show();
            }
        });

        layout_app_custom_server_item1.setOnClickListener(faqOnClickListener);
        layout_app_custom_server_item2.setOnClickListener(faqOnClickListener);
        layout_app_custom_server_item3.setOnClickListener(faqOnClickListener);
        layout_app_custom_server_item4.setOnClickListener(faqOnClickListener);
        layout_app_custom_server_item5.setOnClickListener(faqOnClickListener);
        layout_app_custom_server_item6.setOnClickListener(faqOnClickListener);
        layout_app_custom_server_item7.setOnClickListener(faqOnClickListener);
        layout_app_custom_server_item8.setOnClickListener(faqOnClickListener);
        layout_app_custom_server_item9.setOnClickListener(faqOnClickListener);
        layout_app_custom_server_item10.setOnClickListener(faqOnClickListener);
    }

    void showAppVersion()
    {
        View view = LayoutInflater.from(MainActivity.this).inflate(R.layout.app_version_layout,null,false);
        ImageView button = (ImageView)view.findViewById(R.id.iv_app_version_back);
        TextView tv_app_version_cur = (TextView)view.findViewById(R.id.tv_app_version_cur);
        Button btn_app_version_update = (Button) view.findViewById(R.id.btn_app_version_update);
        //Button btn_save_game_data = (Button)view.findViewById(R.id.btn_save_game_data);
        //Button btn_load_game_data = (Button)view.findViewById(R.id.btn_load_game_data);
        final PopupWindow popupWindow = new PopupWindow(view,ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.MATCH_PARENT,true);
        tv_app_version_cur.setText(String.valueOf(getVersionName(this)));
        popupWindow.setTouchable(true);
        popupWindow.setTouchInterceptor(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return false;
            }
        });
        popupWindow.setBackgroundDrawable(new ColorDrawable(0xFFF8F8F8));
        //popupWindow.showAsDropDown(v);  //showAsDropDown(v,50,0);
        popupWindow.showAtLocation(view,Gravity.CENTER|Gravity.BOTTOM,0,0);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });
        btn_app_version_update.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                checkAppUpdate();
            }
        });
    }
    void showAppLanguage()
    {
        View view = LayoutInflater.from(MainActivity.this).inflate(R.layout.app_language_layout,null,false);
        ImageView button = (ImageView)view.findViewById(R.id.iv_app_language_back);
        ListView lv =  view.findViewById(R.id.lv_pop_lang_sel);
        ArrayList<Map<String, Object>> data =  new ArrayList<Map<String, Object>>();
        //for(int a=0;a<mGlobalVar.getGameGpTotalNum();a++)
        {
            Map<String, Object> map = new HashMap<String, Object>();

            map.put("text", "English");
            if(mGlobalVar.getCurLanguageIndex()<=1)
                map.put("val",true);
            else
                map.put("val",false);
            data.add(map);

            map = new HashMap<String, Object>();

            map.put("text", "简体中文");
            if(mGlobalVar.getCurLanguageIndex()==2)
                map.put("val",true);
            else
                map.put("val",false);
            data.add(map);
        }
        ItemSelAdapter itemSelAdapter = new ItemSelAdapter(MainActivity.this,data);
        lv.setAdapter(itemSelAdapter);

        final PopupWindow popupWindow = new PopupWindow(view,ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.MATCH_PARENT,true);

        popupWindow.setTouchable(true);
        popupWindow.setTouchInterceptor(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return false;
            }
        });
        popupWindow.setBackgroundDrawable(new ColorDrawable(0xFFF8F8F8));
        //popupWindow.showAsDropDown(v);  //showAsDropDown(v,50,0);
        popupWindow.showAtLocation(view,Gravity.CENTER|Gravity.BOTTOM,0,0);
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                // Log.d(TAG,"gameindex ="+String.valueOf(position));
                Resources resources = getBaseContext().getResources();
                Configuration config = resources.getConfiguration();
                DisplayMetrics dm = resources.getDisplayMetrics();
                if((position+1)!=mGlobalVar.getmCurGame()){
                    mGlobalVar.setCurLanguageIndex(position+1);
                    saveUserData(false);
                }

                if(mGlobalVar.getCurLanguageIndex()==1){
                    config.locale = Locale.ENGLISH;
                }
                else if(mGlobalVar.getCurLanguageIndex()==2){
                    config.locale = Locale.CHINA;
                }
                else{
                    config.locale = Locale.getDefault();
                }
                    //resources.updateConfiguration(config, dm);//刷新语言设置信息，这步不能少。
                getBaseContext().createConfigurationContext(config);
                popupWindow.dismiss();

            }
        });
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });
    }

    void showAppStatusInfo()
    {
        //View view = LayoutInflater.from(MainActivity.this).inflate(R.layout.app_status_info_layout,null,false);
        ImageView button = (ImageView)app_status_info.findViewById(R.id.iv_app_status_info_back);
        TextView tv_app_status_info_app_ver_content = app_status_info.findViewById(R.id.tv_app_status_info_app_ver_content);
        TextView tv_app_status_info_phone_name_content = app_status_info.findViewById(R.id.tv_app_status_info_phone_name_content);
        TextView tv_app_status_info_phone_ver_content = app_status_info.findViewById(R.id.tv_app_status_info_phone_ver_content);
        TextView tv_app_status_info_phone_res_content = app_status_info.findViewById(R.id.tv_app_status_info_phone_res_content);
        TextView tv_app_status_info_model_name_content = app_status_info.findViewById(R.id.tv_app_status_info_model_name_content);
        tv_app_status_info_app_ver_content.setText(String.valueOf(getVersionName(this)));
        RelativeLayout app_status_info_device_checksum_layout = app_status_info.findViewById(R.id.app_status_info_device_checksum_layout);
        TextView tv_app_status_info_device_checksum_content = app_status_info.findViewById(R.id.tv_app_status_info_device_checksum_content);

        if(mGlobalVar.getIsLastConDeviceKB())
        {
            app_status_info_device_mode_layout.setVisibility(View.GONE);
            if(mGlobalVar.get_IntVersion()>=((1<<24)|(1<<8)|30))
            {
                app_status_info_device_checksum_layout.setVisibility(View.VISIBLE);
            }
        }
        else
        {
            app_status_info_device_mode_layout.setVisibility(View.VISIBLE);
        }

        if(mGlobalVar.getbIsUsbConnect()) {


            tv_app_status_info_device_ver_content.setText(mGlobalVar.getStrFwVer());
            if(!mGlobalVar.getbIsTransferMode()) {
                CMD_Connect(USBCMD_TIMEOUT);
                SyncPackno();
                long sModel= GetDeviceModel();
                long sDID = GetDeviceID();
                if((sModel==(long)Transfer_Con.HID_BOOT_MODEL_NAME_GM1)||(sModel==(long)Transfer_Con.HID_BOOT_MODEL_NAME_GN1))
                {
                    mGlobalVar.setDeviceName("GM1");
                }
                else if((sModel==(long)Transfer_Con.HID_BOOT_MODEL_NAME_GM2)||(sModel==(long)Transfer_Con.HID_BOOT_MODEL_NAME_GN2))
                {
                    mGlobalVar.setDeviceName("GM2");
                }
                else if(sModel==(long)Transfer_Con.HID_BOOT_MODEL_NAME_HN2)
                {
                    mGlobalVar.setDeviceName("HN2");
                }
                else if(sModel==(long)Transfer_Con.HID_BOOT_MODEL_NAME_MP1)
                {
                    mGlobalVar.setDeviceName("MP1");
                }
                else if(sModel==(long)Transfer_Con.HID_BOOT_MODEL_NAME_BX1)
                {
                    mGlobalVar.setDeviceName("BX1");
                }
                else if(sModel==(long)Transfer_Con.HID_BOOT_MODEL_NAME_BX2)
                {
                    mGlobalVar.setDeviceName("BX2");
                }
                else if(sModel==(long)Transfer_Con.HID_BOOT_MODEL_NAME_MR1)
                {
                    mGlobalVar.setDeviceName("MR1");
                }
                else if(sModel==(long)Transfer_Con.HID_BOOT_MODEL_NAME_U41)
                {
                    mGlobalVar.setDeviceName("U41");
                }
                else
                {
                    if(sDID==0x00C05204)
                    {
                        mGlobalVar.setDeviceName("HN1");
                    }
                    else {
                        mGlobalVar.setDeviceName("NA");
                    }
                }
                if(mGlobalVar.getDeviceIndex()!=mGlobalVar.getLastConnectDeviceIndex())
                {
                    mGlobalVar.setLastConnectDeviceIndex(mGlobalVar.getDeviceIndex());
                    saveUserData(false);
                }
                tv_app_status_info_device_name_content.setText(mGlobalVar.getDeviceName());
                tv_app_status_info_device_connect_content.setText(getResources().getString(R.string.string_pop_connect_already_connect_boot));
            }
            else {
                tv_app_status_info_device_name_content.setText(mGlobalVar.getDeviceName());
                tv_app_status_info_device_connect_content.setText(getResources().getString(R.string.string_pop_connect_already_connect));
            }
            if(mGlobalVar.getIsLastConDeviceKB())
            {
                if(mGlobalVar.tranGet_Value(Transfer_Con.HID_CMD_GET_HW_SETTING,0,0xFF,g_u8DataBuf))
                {
                    if((g_u8DataBuf[0]&0x01)==0x01)
                    {
                        tv_app_status_info_device_type_content.setText(getResources().getString(R.string.string_app_status_info_office_mode));
                    }
                    else
                    {
                        tv_app_status_info_device_type_content.setText(getResources().getString(R.string.string_app_status_info_game_mode));
                    }
                }
                if(mGlobalVar.get_IntVersion()>=((1<<24)|(1<<8)|30)) {
                    if (mGlobalVar.tranGet_Value(Transfer_Con.HID_CMD_GET_CHECKSUM, 0x4000, g_lCodeLen, g_u8DataBuf)) {
                        int cks = ((g_u8DataBuf[1] & 0xff) << 8) | (g_u8DataBuf[0] & 0xff);
                        tv_app_status_info_device_checksum_content.setText(String.format("0x%04X",cks));
                    }
                }
            }
            else {
                if (mGlobalVar.tranGet_Value(Transfer_Con.HID_CMD_GET_HW_SETTING, 0, 0x80, g_u8DataBuf)) {
                    if ((g_u8DataBuf[0] & 0x80) == 0x80) {
                        tv_app_status_info_device_type_content.setText(getResources().getString(R.string.string_connect_mode_gp_normal));
                    } else {
                        tv_app_status_info_device_type_content.setText(getResources().getString(R.string.string_connect_mode_gp_touch));
                    }
                }
                if (mGlobalVar.getIsInjectMode())
                    tv_app_status_info_device_mode_content.setText(getResources().getString(R.string.string_connect_mode_inject));
                else
                    tv_app_status_info_device_mode_content.setText(getResources().getString(R.string.string_connect_mode_normal));
            }
        }
        else {
            tv_app_status_info_device_name_content.setText(getResources().getString(R.string.string_app_status_info_content_unknown));
            tv_app_status_info_device_ver_content.setText(getResources().getString(R.string.string_app_status_info_content_unknown));
            tv_app_status_info_device_connect_content.setText(getResources().getString(R.string.string_pop_connect_disconnect));
            tv_app_status_info_device_type_content.setText(getResources().getString(R.string.string_app_status_info_content_unknown));
            tv_app_status_info_device_mode_content.setText(getResources().getString(R.string.string_app_status_info_content_unknown));
        }
        tv_app_status_info_model_name_content.setText(android.os.Build.BRAND+" "+Build.ID);
        tv_app_status_info_phone_ver_content.setText(String.valueOf(Build.VERSION.RELEASE));
        tv_app_status_info_phone_res_content.setText(String.format("%dX%d",mRes_Hei,mRes_Wid));

        final PopupWindow popupWindow = new PopupWindow(app_status_info,ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.MATCH_PARENT,true);

        popupWindow.setTouchable(true);
        popupWindow.setTouchInterceptor(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return false;
            }
        });
        popupWindow.setBackgroundDrawable(new ColorDrawable(0xFFF8F8F8));
        //popupWindow.showAsDropDown(v);  //showAsDropDown(v,50,0);
        popupWindow.showAtLocation(app_status_info,Gravity.CENTER|Gravity.BOTTOM,0,0);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });
    }

    boolean bIsSwapChecked =  false;
    void showRockerSetting()
    {
        View view = LayoutInflater.from(MainActivity.this).inflate(R.layout.rocker_setting_layout,null,false);
        ImageView button = (ImageView)view.findViewById(R.id.iv_rocker_setting_back);
        final SeekBar sb_rocker_setting_min = (SeekBar)view.findViewById(R.id.sb_rocker_setting_min);
        final SeekBar sb_rocker_setting_max = (SeekBar)view.findViewById(R.id.sb_rocker_setting_max);
        final SeekBar sb_rocker_setting_time = (SeekBar)view.findViewById(R.id.sb_rocker_setting_time);
        final SeekBar sb_rocker_setting_left_range = view.findViewById(R.id.sb_rocker_setting_left_range);
        ImageView iv_rocker_setting_min_del = (ImageView)view.findViewById(R.id.iv_rocker_setting_min_del);
        ImageView iv_rocker_setting_min_add = (ImageView)view.findViewById(R.id.iv_rocker_setting_min_add);
        ImageView iv_rocker_setting_max_del = (ImageView)view.findViewById(R.id.iv_rocker_setting_max_del);
        ImageView iv_rocker_setting_max_add = (ImageView)view.findViewById(R.id.iv_rocker_setting_max_add);

        ImageView iv_rocker_setting_time_del = (ImageView)view.findViewById(R.id.iv_rocker_setting_time_del);
        ImageView iv_rocker_setting_time_add = (ImageView)view.findViewById(R.id.iv_rocker_setting_time_add);

        LinearLayout ll_rocker_setting_swap_layout = view.findViewById(R.id.ll_rocker_setting_swap_layout);
        RelativeLayout rl_rocker_setting_left_ups = view.findViewById(R.id.rl_rocker_setting_left_ups);
        RelativeLayout rl_rocker_setting_left_range = view.findViewById(R.id.rl_rocker_setting_left_range);
        CheckBox ckb_rocker_setting_swap = view.findViewById(R.id.ckb_rocker_setting_swap);
        CheckBox ckb_rocker_setting_left_ups = view.findViewById(R.id.ckb_rocker_setting_left_ups);
        final TextView tv_rocker_setting_left_range = view.findViewById(R.id.tv_rocker_setting_left_range);
        final TextView tv_rocker_setting_min_value = view.findViewById(R.id.tv_rocker_setting_min_value);
        final TextView tv_rocker_setting_max_value = view.findViewById(R.id.tv_rocker_setting_max_value);
        final TextView tv_rocker_setting_time_value = view.findViewById(R.id.tv_rocker_setting_time_value);
        LinearLayout ll_rocker_setting_r_rock_range  = view.findViewById(R.id.ll_rocker_setting_r_rock_range);
        RadioButton rb_rocker_setting_r_rocker_range_full = view.findViewById(R.id.rb_rocker_setting_r_rocker_range_full);
        RadioButton rb_rocker_setting_r_rocker_range_limited = view.findViewById(R.id.rb_rocker_setting_r_rocker_range_limited);
        if(mGlobalVar.getIsSupportMenuKey())
        {
            ll_rocker_setting_swap_layout.setVisibility(View.VISIBLE);
        }

        if((mGlobalVar.getDeviceIndex()==Transfer_Con.DEVICE_GM1_INDEX)||(mGlobalVar.getDeviceIndex()==Transfer_Con.DEVICE_HN2_INDEX)||((mGlobalVar.getDeviceIndex()==Transfer_Con.DEVICE_HN1_INDEX)&&(mGlobalVar.get_IntVersion()>(mGlobalVar.SUPPORT_MENU_KEY_VER+1))))
        {
            ll_rocker_setting_r_rock_range.setVisibility(View.VISIBLE);
        }

        if((mGlobalVar.getDeviceIndex()==Transfer_Con.DEVICE_HN1_INDEX)||(mGlobalVar.getDeviceIndex()==Transfer_Con.DEVICE_HN2_INDEX))
        {
           if(mGlobalVar.get_IntVersion()>=((1<<24)+(1<<8)+19)) {
               rl_rocker_setting_left_ups.setVisibility(View.VISIBLE);
               rl_rocker_setting_left_range.setVisibility(View.VISIBLE);
           }
        }
        if((mGlobalVar.getDeviceIndex()==Transfer_Con.DEVICE_GM1_INDEX))
        {
            if(mGlobalVar.get_IntVersion()>=((1<<24)+(1<<8)+19)) {
                rl_rocker_setting_left_ups.setVisibility(View.VISIBLE);
                rl_rocker_setting_left_range.setVisibility(View.VISIBLE);
            }
        }

        if(Build.VERSION.SDK_INT >= 26)
        {
            sb_rocker_setting_min.setMin(2);
            sb_rocker_setting_max.setMin(20);
            sb_rocker_setting_time.setMin(1);
            sb_rocker_setting_left_range.setMin(1);
        }
            sb_rocker_setting_min.setMax(20);
        sb_rocker_setting_max.setMax(100);
        sb_rocker_setting_time.setMax(60);
        sb_rocker_setting_left_range.setMax(60);
        if(mGlobalVar.tranGet_Value((byte)(Transfer_Con.HID_CMD_GET_R_ROCK_MIN),0,0,g_u8DataBuf))
        {
            sb_rocker_setting_min.setProgress(g_u8DataBuf[0]);
            tv_rocker_setting_min_value.setText(String.valueOf((g_u8DataBuf[0]-2)*100/(sb_rocker_setting_min.getMax()-2))+"%");
        }
        if(mGlobalVar.tranGet_Value((byte)(Transfer_Con.HID_CMD_GET_R_ROCK_MAX),0,0,g_u8DataBuf))
        {
            sb_rocker_setting_max.setProgress(g_u8DataBuf[0]);
            tv_rocker_setting_max_value.setText(String.valueOf((g_u8DataBuf[0]-20)*100/(sb_rocker_setting_max.getMax()-20))+"%");
        }
        if(mGlobalVar.tranGet_Value((byte)(Transfer_Con.HID_CMD_GET_R_ROCK_TIME),0,0,g_u8DataBuf))
        {
            sb_rocker_setting_time.setProgress(g_u8DataBuf[0]);
            tv_rocker_setting_time_value.setText(String.valueOf((g_u8DataBuf[0]-1)*100/(sb_rocker_setting_time.getMax()-1))+"%");
        }
        if(mGlobalVar.tranGet_Value((byte)(Transfer_Con.HID_CMD_GET_LEFT_VSEN),0,0,g_u8DataBuf))
        {
            sb_rocker_setting_left_range.setProgress(g_u8DataBuf[0]);
            tv_rocker_setting_left_range.setText(String.valueOf(g_u8DataBuf[0]*100/sb_rocker_setting_left_range.getMax())+"%");
        }
        if(mGlobalVar.tranGet_Value((byte)(Transfer_Con.HID_CMD_GET_HW_SETTING),0xFF,0xFF,g_u8DataBuf))
        {
            if((g_u8DataBuf[0]&0x40)==0x40)
            {
                ckb_rocker_setting_swap.setChecked(true);
                bIsSwapChecked = true;
            }
            else
            {
                ckb_rocker_setting_swap.setChecked(false);
                bIsSwapChecked = false;
            }
            if((g_u8DataBuf[0]&0x08)==0x08)
                rb_rocker_setting_r_rocker_range_limited.setChecked(true);
            else
                rb_rocker_setting_r_rocker_range_full.setChecked(true);

            if((g_u8DataBuf[0]&0x02)==0x02)
                ckb_rocker_setting_left_ups.setChecked(true);
            else
                ckb_rocker_setting_left_ups.setChecked(false);
        }


        final PopupWindow popupWindow = new PopupWindow(view,ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.MATCH_PARENT,true);
        popupWindow.setTouchable(true);
        popupWindow.setTouchInterceptor(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return false;
            }
        });
        popupWindow.setBackgroundDrawable(new ColorDrawable(0xFFF8F8F8));
        //popupWindow.showAsDropDown(v);  //showAsDropDown(v,50,0);
        popupWindow.showAtLocation(view,Gravity.CENTER|Gravity.BOTTOM,0,0);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });

        sb_rocker_setting_min.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                mGlobalVar.tranSet_Value(Transfer_Con.HID_CMD_SET_R_ROCK_MIN,(progress<1?1:progress),0);
                tv_rocker_setting_min_value.setText(String.valueOf((progress-2)*100/(sb_rocker_setting_min.getMax()-2))+"%");
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
        sb_rocker_setting_max.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                mGlobalVar.tranSet_Value(Transfer_Con.HID_CMD_SET_R_ROCK_MAX,(progress<1?1:progress),0);
                tv_rocker_setting_max_value.setText(String.valueOf((progress-20)*100/(sb_rocker_setting_max.getMax()-20))+"%");
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });

        sb_rocker_setting_time.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                mGlobalVar.tranSet_Value(Transfer_Con.HID_CMD_SET_R_ROCK_TIME,(progress<1?1:progress),0);
                tv_rocker_setting_time_value.setText(String.valueOf((progress-1)*100/(sb_rocker_setting_time.getMax()-1))+"%");
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });

        iv_rocker_setting_min_del.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int data = sb_rocker_setting_min.getProgress();
                if(Build.VERSION.SDK_INT >= 26) {
                    if (data > sb_rocker_setting_min.getMin()) {
                        data--;
                        sb_rocker_setting_min.setProgress(data);
                    }
                }
                else
                {
                    if (data > 0) {
                        data--;
                        sb_rocker_setting_min.setProgress(data);
                    }
                }
            }
        });
        iv_rocker_setting_max_del.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int data = sb_rocker_setting_max.getProgress();
                if(Build.VERSION.SDK_INT >= 26) {
                if(data>sb_rocker_setting_max.getMin()) {
                    data--;
                    sb_rocker_setting_max.setProgress(data);
                }
                else
                {
                    if (data > 0) {
                        data--;
                        sb_rocker_setting_min.setProgress(data);
                    }
                }
                }
            }
        });
        iv_rocker_setting_min_add.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            int data = sb_rocker_setting_min.getProgress();
            if(data<sb_rocker_setting_min.getMax()) {
                data++;
                sb_rocker_setting_min.setProgress(data);
            }
        }
    });
        iv_rocker_setting_max_add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int data = sb_rocker_setting_max.getProgress();
                if(data<sb_rocker_setting_max.getMax()) {
                    data++;
                    sb_rocker_setting_max.setProgress(data);
                }
            }
        });


        iv_rocker_setting_time_del.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int data = sb_rocker_setting_time.getProgress();
                if(Build.VERSION.SDK_INT >= 26) {
                    if (data > sb_rocker_setting_time.getMin()) {
                        data--;
                        sb_rocker_setting_time.setProgress(data);
                    }
                }
                else
                {
                    if (data > 0) {
                        data--;
                        sb_rocker_setting_time.setProgress(data);
                    }
                }
            }
        });
        iv_rocker_setting_time_add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int data = sb_rocker_setting_time.getProgress();
                if(data<sb_rocker_setting_time.getMax()) {
                    data++;
                    sb_rocker_setting_time.setProgress(data);
                }
            }
        });



        ckb_rocker_setting_swap.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if(bIsSwapChecked&&(!isChecked))
                {
                    if(mGlobalVar.tranSet_Value(Transfer_Con.HID_CMD_SET_HW_SETTING,0x00,0x40))
                    {
                        bIsSwapChecked = false;
                    }
                }
                else if(!bIsSwapChecked&&(isChecked))
                {
                    if(mGlobalVar.tranSet_Value(Transfer_Con.HID_CMD_SET_HW_SETTING,0x40,0x40))
                    {
                        bIsSwapChecked = true;
                    }
                }
            }
        });

        ckb_rocker_setting_left_ups.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if(isChecked)
                {
                    mGlobalVar.tranSet_Value(Transfer_Con.HID_CMD_SET_HW_SETTING,0x02,0x02);
                }
                else
                {
                    mGlobalVar.tranSet_Value(Transfer_Con.HID_CMD_SET_HW_SETTING,0x00,0x02);
                }
            }
        });

        rb_rocker_setting_r_rocker_range_full.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if(isChecked)
                    mGlobalVar.tranSet_Value((byte)(Transfer_Con.HID_CMD_SET_HW_SETTING),0,0x08);
            }
        });

        rb_rocker_setting_r_rocker_range_limited.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if(isChecked)
                    mGlobalVar.tranSet_Value((byte)(Transfer_Con.HID_CMD_SET_HW_SETTING),0x08,0x08);
            }
        });

        sb_rocker_setting_left_range.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                mGlobalVar.tranSet_Value((byte)(Transfer_Con.HID_CMD_SET_LEFT_VSEN),progress,0);
                tv_rocker_setting_left_range.setText(String.valueOf(progress*100/sb_rocker_setting_left_range.getMax())+"%");
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
    }

    void showIconSetting()
    {
        View view = LayoutInflater.from(MainActivity.this).inflate(R.layout.icon_size_setting_layout,null,false);
        ImageView button = view.findViewById(R.id.iv_icon_size_setting_back);
        SeekBar sb_icon_size_setting_logo =view.findViewById(R.id.sb_icon_size_setting_logo);
        SeekBar sb_icon_size_setting_normal =view.findViewById(R.id.sb_icon_size_setting_normal);
        SeekBar sb_icon_size_setting_edit =view.findViewById(R.id.sb_icon_size_setting_edit);
        SeekBar sb_icon_alpha_setting_normal =view.findViewById(R.id.sb_icon_alpha_setting_normal);
        SeekBar sb_icon_alpha_setting_edit =view.findViewById(R.id.sb_icon_alpha_setting_edit);
        final TextView tv_icon_size_setting_logo =view.findViewById(R.id.tv_icon_size_setting_logo);
        final TextView tv_icon_size_setting_normal =view.findViewById(R.id.tv_icon_size_setting_normal);
        final TextView tv_icon_alpha_setting_normal =view.findViewById(R.id.tv_icon_alpha_setting_normal);
        final TextView tv_icon_size_setting_edit =view.findViewById(R.id.tv_icon_size_setting_edit);
        final TextView tv_icon_alpha_setting_edit =view.findViewById(R.id.tv_icon_alpha_setting_edit);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            sb_icon_size_setting_logo.setMin(1);
            sb_icon_size_setting_normal.setMin(1);
            sb_icon_size_setting_edit.setMin(1);
            sb_icon_alpha_setting_normal.setMin(1);
            sb_icon_alpha_setting_edit.setMin(1);
        }
        sb_icon_size_setting_logo.setMax(10);
        sb_icon_size_setting_normal.setMax(10);
        sb_icon_size_setting_edit.setMax(10);
        sb_icon_alpha_setting_normal.setMax(10);
        sb_icon_alpha_setting_edit.setMax(10);

        sb_icon_size_setting_logo.setProgress(mGlobalVar.getFloat_Icon_Size());
        tv_icon_size_setting_logo.setText(String.valueOf(sb_icon_size_setting_logo.getProgress()));
        sb_icon_size_setting_normal.setProgress(mGlobalVar.getNormal_Icon_Size());
        tv_icon_size_setting_normal.setText(String.valueOf(sb_icon_size_setting_normal.getProgress()));
        sb_icon_alpha_setting_normal.setProgress(mGlobalVar.getNormal_Icon_Alpha());
        tv_icon_alpha_setting_normal.setText(String.valueOf(sb_icon_alpha_setting_normal.getProgress()));
        sb_icon_size_setting_edit.setProgress(mGlobalVar.getPt_Tbl_View_Size());
        tv_icon_size_setting_edit.setText(String.valueOf(sb_icon_size_setting_edit.getProgress()));
        sb_icon_alpha_setting_edit.setProgress(mGlobalVar.getPt_Tbl_View_Alpha());
        tv_icon_alpha_setting_edit.setText(String.valueOf(sb_icon_alpha_setting_edit.getProgress()));

        final PopupWindow popupWindow = new PopupWindow(view,ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.MATCH_PARENT,true);
        popupWindow.setTouchable(true);
        popupWindow.setTouchInterceptor(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return false;
            }
        });
        popupWindow.setBackgroundDrawable(new ColorDrawable(0xFFF8F8F8));
        //popupWindow.showAsDropDown(v);  //showAsDropDown(v,50,0);
        popupWindow.showAtLocation(view,Gravity.CENTER|Gravity.BOTTOM,0,0);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
                saveUserData(false);
            }
        });

        sb_icon_size_setting_logo.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                tv_icon_size_setting_logo.setText(String.valueOf(progress));
                mGlobalVar.setFloat_Icon_Size(progress);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                saveUserData(false);
            }
        });
        sb_icon_size_setting_normal.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                tv_icon_size_setting_normal.setText(String.valueOf(progress));
                mGlobalVar.setNormal_Icon_Size(progress);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                saveUserData(false);
            }
        });
        sb_icon_alpha_setting_normal.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                tv_icon_alpha_setting_normal.setText(String.valueOf(progress));
                mGlobalVar.setNormal_Icon_Alpha(progress);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                saveUserData(false);
            }
        });
        sb_icon_size_setting_edit.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                tv_icon_size_setting_edit.setText(String.valueOf(progress));
                mGlobalVar.setPt_Tbl_View_Size(progress);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                saveUserData(false);
            }
        });
        sb_icon_alpha_setting_edit.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                tv_icon_alpha_setting_edit.setText(String.valueOf(progress));
                mGlobalVar.setPt_Tbl_View_Alpha(progress);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
    }


    public boolean getIsHDMIOut()
    {
        MediaRouter router = (MediaRouter)getSystemService(MEDIA_ROUTER_SERVICE);
        local_width = mGlobalVar.getManualHDMIWidth();
        local_height = mGlobalVar.getManualHDMIHeight();
        bIsDetectHDMIIn = false;
        if(router!=null)
        {
            CharSequence strName = "HDMI";
            if(router.getDefaultRoute().getPresentationDisplay()!=null) {
                if (router.getDefaultRoute().getPresentationDisplay().getName().contains(strName)) {
                    Display display = router.getDefaultRoute().getPresentationDisplay();
                    if (display == null) {
                        return false;
                    } else {
                        Log.d(TAG, display.toString());
                        Point point = new Point();
                        display.getRealSize(point);
                        local_width = point.x;
                        local_height = point.y;
                        bIsDetectHDMIIn = true;
                        return true;
                    }
                } else {
                    return false;
                }
            }
        }
        return false;
    }
    public int getItemID(List<Map<String, Object>> data_list, int pos)
    {
        return (int)data_list.get(pos).get("id");
    }

    int local_width=1920,local_height=1080;
    boolean bIsDetectHDMIIn = false;

    void showDeviceButtonSetting() {
        if (mGlobalVar.getIsCurDeviceKB()) {
            View view = LayoutInflater.from(MainActivity.this).inflate(R.layout.device_button_setting_kb_layout, null, false);
            ImageView button = (ImageView) view.findViewById(R.id.iv_device_button_setting_kb_back);
            final ImageView iv_device_button_setting_kb_btn =view.findViewById(R.id.iv_device_button_setting_kb_btn);
            LinearLayout device_button_setting_kb_tvmode_layout = view.findViewById(R.id.device_button_setting_kb_tvmode_layout);
            LinearLayout layout_device_button_setting_kb_switch_to_mouse = view.findViewById(R.id.layout_device_button_setting_kb_switch_to_mouse);
            final LinearLayout layout_device_button_setting_kb_tvmode_resolution = view.findViewById(R.id.layout_device_button_setting_kb_tvmode_resolution);
            final  RelativeLayout device_button_setting_kb_tvmode_manual_layout = view.findViewById(R.id.device_button_setting_kb_tvmode_manual_layout);
            RadioButton rb_device_button_setting_kb_esc = view.findViewById(R.id.rb_device_button_setting_kb_esc);
            RadioButton rb_device_button_setting_kb_wheel = view.findViewById(R.id.rb_device_button_setting_kb_wheel);
            final Switch sw_device_button_setting_kb_tvmode = view.findViewById(R.id.sw_device_button_setting_kb_tvmode);
            Switch sw_device_button_setting_kb_tvmode_auto = view.findViewById(R.id.sw_device_button_setting_kb_tvmode_auto);
            final TextView tv_device_button_setting_kb_tvmode_manual_value = view.findViewById(R.id.tv_device_button_setting_kb_tvmode_manual_value);
            final TextView tv_device_button_setting_kb_tvmode_auto_value = view.findViewById(R.id.tv_device_button_setting_kb_tvmode_auto_value);
            final EditText et_device_button_setting_kb_width = view.findViewById(R.id.et_device_button_setting_kb_width);
            final EditText et_device_button_setting_kb_height = view.findViewById(R.id.et_device_button_setting_kb_height);
            TextView tv_device_button_setting_kb_tvmode_resolution = view.findViewById(R.id.tv_device_button_setting_kb_tvmode_resolution);

            LinearLayout device_button_setting_kb_rocker_range_layout = view.findViewById(R.id.device_button_setting_kb_rocker_range_layout);
            LinearLayout device_button_setting_kb_force_2touch_layout = view.findViewById(R.id.device_button_setting_kb_force_2touch_layout);
            SeekBar sb_device_button_setting_kb_rocker_range_value = view.findViewById(R.id.sb_device_button_setting_kb_rocker_range_value);
            final TextView tv_device_button_setting_kb_rocker_range_value = view.findViewById(R.id.tv_device_button_setting_kb_rocker_range_value);
            Switch sw_device_button_setting_kb_force_2touch = view.findViewById(R.id.sw_device_button_setting_kb_force_2touch);

            LinearLayout device_button_setting_kb_virtual_mouse_layout = view.findViewById(R.id.device_button_setting_kb_virtual_mouse_layout);
            Switch sw_device_button_setting_kb_virtual_mouse = view.findViewById(R.id.sw_device_button_setting_kb_virtual_mouse);

            RelativeLayout device_button_setting_kb_virtual_mouse_speed_layout = view.findViewById(R.id.device_button_setting_kb_virtual_mouse_speed_layout);
            SeekBar sb_device_button_setting_kb_virtual_mouse_speed = view.findViewById(R.id.sb_device_button_setting_kb_virtual_mouse_speed);
            final TextView tv_device_button_setting_kb_virtual_mouse_speed_value = view.findViewById(R.id.tv_device_button_setting_kb_virtual_mouse_speed_value);
            if(Transfer_Con.ENABLE_MANUAL_TV_SWITCH) {
                if (mGlobalVar.getIsSupportSwitchTVMode_KB()) {
                    device_button_setting_kb_tvmode_layout.setVisibility(View.VISIBLE);
                } else {
                    device_button_setting_kb_tvmode_layout.setVisibility(View.GONE);
                }
            }

            if(mGlobalVar.getIsSupportMouseSideKeyAndHorSense())
            {
                layout_device_button_setting_kb_switch_to_mouse.setVisibility(View.VISIBLE);
                if(mGlobalVar.tranGet_Value_retry(Transfer_Con.HID_CMD_GET_MOUSE_SW_KEY,0,0,g_u8DataBuf,5))
                {
                    TypedArray ar;
                    int index;
                    cb_device_button_setting_kb_switch_to_mouse_press.setChecked((g_u8DataBuf[0]&0x80)==0x80);
                    ar = getResources().obtainTypedArray(R.array.mp1_button_images);
                    index = mGlobalVar.switchMouseToKeyEvent(g_u8DataBuf[0]&0xff,g_u8DataBuf[4]&0xff);
                    iv_device_button_setting_kb_btn.setImageResource(ar.getResourceId(index, 0));
                    ar.recycle();
                }
            }
            else
            {
                layout_device_button_setting_kb_switch_to_mouse.setVisibility(View.GONE);
            }

            if(mGlobalVar.tranGet_Value_retry(Transfer_Con.HID_CMD_GET_HW_SETTING,0,0xFF,g_u8DataBuf,5))
            {
                if ((g_u8DataBuf[0] & 0x02) == 0x02) {
                    rb_device_button_setting_kb_wheel.setChecked(true);
                } else {
                    rb_device_button_setting_kb_esc.setChecked(true);
                }
                if((g_u8DataBuf[0]&0x04)==0x04)
                {
                    sw_device_button_setting_kb_tvmode.setChecked(true);
                    tv_device_button_setting_kb_tvmode_manual_value.setText(getResources().getString(R.string.str_device_button_setting_kb_screen_projection));
                }
                else
                {
                    sw_device_button_setting_kb_tvmode.setChecked(false);
                    tv_device_button_setting_kb_tvmode_manual_value.setText(getResources().getString(R.string.str_device_button_setting_kb_mobile));
                }
                //Toast.makeText(MainActivity.this,String.format("0x%x,0x%x,0x%x,0x%x",g_u8DataBuf[0],g_u8DataBuf[1],g_u8DataBuf[2],g_u8DataBuf[3]),Toast.LENGTH_SHORT).show();
            }
            if(mGlobalVar.getIsCurDeviceKBBox()) {
                getIsHDMIOut();
                if (mGlobalVar.getIsAutoSwitchToHDMI()) {
                    device_button_setting_kb_tvmode_manual_layout.setEnabled(false);
                    sw_device_button_setting_kb_tvmode_auto.setChecked(true);
                    tv_device_button_setting_kb_tvmode_auto_value.setText(getResources().getString(R.string.str_device_button_setting_kb_auto));
                    tv_device_button_setting_kb_tvmode_manual_value.setEnabled(false);
                    sw_device_button_setting_kb_tvmode.setEnabled(false);
                    layout_device_button_setting_kb_tvmode_resolution.setVisibility(View.GONE);
                    if (bIsDetectHDMIIn) {
                        sw_device_button_setting_kb_tvmode.setChecked(true);
                        tv_device_button_setting_kb_tvmode_manual_value.setText(getResources().getString(R.string.str_device_button_setting_kb_screen_projection));
                        if ((g_u8DataBuf[0] & 0x04) != 0x04)
                            mGlobalVar.tranSet_Value(Transfer_Con.HID_CMD_SET_HW_SETTING, 0x04, 0x04);
                    } else {
                        sw_device_button_setting_kb_tvmode.setChecked(false);
                        tv_device_button_setting_kb_tvmode_manual_value.setText(getResources().getString(R.string.str_device_button_setting_kb_mobile));
                        if ((g_u8DataBuf[0] & 0x04) == 0x04)
                            mGlobalVar.tranSet_Value(Transfer_Con.HID_CMD_SET_HW_SETTING, 0x00, 0x04);
                    }
                } else {
                    device_button_setting_kb_tvmode_manual_layout.setEnabled(true);
                    sw_device_button_setting_kb_tvmode_auto.setChecked(false);
                    layout_device_button_setting_kb_tvmode_resolution.setVisibility(View.VISIBLE);
                    tv_device_button_setting_kb_tvmode_auto_value.setText(getResources().getString(R.string.str_device_button_setting_kb_manual));
                    if ((g_u8DataBuf[0] & 0x04) == 0x04)
                    {
                        sw_device_button_setting_kb_tvmode.setChecked(true);
                        tv_device_button_setting_kb_tvmode_manual_value.setText(getResources().getString(R.string.str_device_button_setting_kb_screen_projection));
                        mGlobalVar.setIsManualSetToHDMI(true);
                    }
                    else
                    {
                        sw_device_button_setting_kb_tvmode.setChecked(false);
                        tv_device_button_setting_kb_tvmode_manual_value.setText(getResources().getString(R.string.str_device_button_setting_kb_mobile));
                        mGlobalVar.setIsManualSetToHDMI(false);
                    }

                }
                et_device_button_setting_kb_width.setKeyListener(DigitsKeyListener.getInstance("1234567890"));
                et_device_button_setting_kb_height.setKeyListener(DigitsKeyListener.getInstance("1234567890"));
                et_device_button_setting_kb_width.setHint(String.valueOf(mGlobalVar.getManualHDMIWidth()));
                et_device_button_setting_kb_height.setHint(String.valueOf(mGlobalVar.getManualHDMIHeight()));
                if(bIsDetectHDMIIn)
                    tv_device_button_setting_kb_tvmode_resolution.setText(String.format((getResources().getString(R.string.str_device_button_setting_resolution_of_display)+"%dX%d"),local_width,local_height));
                else
                    tv_device_button_setting_kb_tvmode_resolution.setText(String.format(getResources().getString(R.string.str_device_button_setting_monitor_not_connected)));
            }

            final Handler handler = new Handler();
            final Runnable delayRun = new Runnable() {
                @Override
                public void run() {
                    String defStr = String.valueOf(mGlobalVar.getManualHDMIWidth());
                    if (!android.text.TextUtils.isEmpty(et_device_button_setting_kb_width.getText()))
                        defStr = et_device_button_setting_kb_width.getText().toString();
                    local_width = Integer.parseInt(defStr);

                    defStr = String.valueOf(mGlobalVar.getManualHDMIHeight());
                    if (!android.text.TextUtils.isEmpty(et_device_button_setting_kb_height.getText()))
                        defStr = et_device_button_setting_kb_height.getText().toString();
                    local_height = Integer.parseInt(defStr);

                    mGlobalVar.setManualSetHDMIWidth(local_width);
                    mGlobalVar.setManualSetHDMIHeight(local_height);
                }
            };

            et_device_button_setting_kb_width.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                }

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {

                }

                @Override
                public void afterTextChanged(Editable s) {
                    if(delayRun!=null){
                        //每次editText有变化的时候，则移除上次发出的延迟线程
                        handler.removeCallbacks(delayRun);
                    }
                    //延迟600ms，如果不再输入字符，则执行该线程的run方法
                    handler.postDelayed(delayRun, 1000);
                }
            });

            et_device_button_setting_kb_height.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                }

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {

                }

                @Override
                public void afterTextChanged(Editable s) {
                    if(delayRun!=null){
                        //每次editText有变化的时候，则移除上次发出的延迟线程
                        handler.removeCallbacks(delayRun);
                    }
                    //延迟600ms，如果不再输入字符，则执行该线程的run方法
                    handler.postDelayed(delayRun, 1000);
                }
            });

            if(mGlobalVar.getIsSupportMultiShotHelp_KB())
            {
                device_button_setting_kb_rocker_range_layout.setVisibility(View.VISIBLE);
                sb_device_button_setting_kb_rocker_range_value.setProgress(mGlobalVar.getRockerMoveRange_KB());
                tv_device_button_setting_kb_rocker_range_value.setText(String.format("%d%%",mGlobalVar.getRockerMoveRange_KB()));

                device_button_setting_kb_force_2touch_layout.setVisibility(View.VISIBLE);
                sw_device_button_setting_kb_force_2touch.setChecked(mGlobalVar.getIsForceViewOut());
            }

            if(mGlobalVar.getIsSupportVirtualMouse_KB())
            {
                device_button_setting_kb_virtual_mouse_layout.setVisibility(View.VISIBLE);
                sw_device_button_setting_kb_virtual_mouse.setChecked(mGlobalVar.getIsUseVirtualMouse());
                if(Transfer_Con.ENABLE_VIRTUAL_MOUSE_SPEED)
                {
                    //device_button_setting_kb_virtual_mouse_speed_layout.setVisibility(View.VISIBLE);
                    sb_device_button_setting_kb_virtual_mouse_speed.setProgress(mGlobalVar.getVirtualMouseInterval());
                    tv_device_button_setting_kb_virtual_mouse_speed_value.setText(String.valueOf(mGlobalVar.getVirtualMouseInterval()));
                }
            }

            final PopupWindow popupWindow = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, true);
            popupWindow.setTouchable(true);
            popupWindow.setTouchInterceptor(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    return false;
                }
            });
            popupWindow.setBackgroundDrawable(new ColorDrawable(0xFFF8F8F8));
            //popupWindow.showAsDropDown(v);  //showAsDropDown(v,50,0);
            popupWindow.showAtLocation(view, Gravity.CENTER | Gravity.BOTTOM, 0, 0);
            button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    popupWindow.dismiss();
                }
            });

            rb_device_button_setting_kb_wheel.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mGlobalVar.tranSet_Value(Transfer_Con.HID_CMD_SET_HW_SETTING,  0x02, 0x02);
                }
            });

            rb_device_button_setting_kb_esc.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mGlobalVar.tranSet_Value(Transfer_Con.HID_CMD_SET_HW_SETTING,  0x00, 0x02);
                }
            });

            sw_device_button_setting_kb_tvmode.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    if(isChecked)
                    {
                        String defStr = String.valueOf(mGlobalVar.getManualHDMIWidth());
                        if (!android.text.TextUtils.isEmpty(et_device_button_setting_kb_width.getText()))
                            defStr = et_device_button_setting_kb_width.getText().toString();
                        local_width = Integer.parseInt(defStr);

                        defStr = String.valueOf(mGlobalVar.getManualHDMIHeight());
                        if (!android.text.TextUtils.isEmpty(et_device_button_setting_kb_height.getText()))
                            defStr = et_device_button_setting_kb_height.getText().toString();
                        local_height = Integer.parseInt(defStr);

                        mGlobalVar.setManualSetHDMIWidth(local_width);
                        mGlobalVar.setManualSetHDMIHeight(local_height);

                        mGlobalVar.tranSet_Value(Transfer_Con.HID_CMD_SET_HW_SETTING,  0x04, 0x04);
                        mGlobalVar.tranSet_Value(Transfer_Con.HID_CMD_SET_HDMI_RESOLUTION, local_width, local_height);
                        tv_device_button_setting_kb_tvmode_manual_value.setText(getResources().getString(R.string.str_device_button_setting_kb_screen_projection));
                    }
                    else
                    {
                        mGlobalVar.tranSet_Value(Transfer_Con.HID_CMD_SET_HW_SETTING,  0x00, 0x04);
                        tv_device_button_setting_kb_tvmode_manual_value.setText(getResources().getString(R.string.str_device_button_setting_kb_mobile));
                    }
                    mGlobalVar.setIsManualSetToHDMI(isChecked);
                    saveUserData(false);
                }
            });

            sw_device_button_setting_kb_tvmode_auto.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    mGlobalVar.setIsAutoSwitchToHDMI(isChecked);
                    if(isChecked) {
                        tv_device_button_setting_kb_tvmode_auto_value.setText(getResources().getString(R.string.str_device_button_setting_kb_auto));
                        sw_device_button_setting_kb_tvmode.setEnabled(false);
                        tv_device_button_setting_kb_tvmode_manual_value.setEnabled(false);
                        layout_device_button_setting_kb_tvmode_resolution.setVisibility(View.GONE);
                        if(getIsHDMIOut())
                        {
                            sw_device_button_setting_kb_tvmode.setChecked(true);
                            mGlobalVar.tranSet_Value(Transfer_Con.HID_CMD_SET_HDMI_RESOLUTION, local_width, local_height);
                            mGlobalVar.tranSet_Value(Transfer_Con.HID_CMD_SET_HW_SETTING,  0x04, 0x04);
                            tv_device_button_setting_kb_tvmode_manual_value.setText(getResources().getString(R.string.str_device_button_setting_kb_screen_projection));
                        }
                        else
                        {
                            sw_device_button_setting_kb_tvmode.setChecked(false);
                            mGlobalVar.tranSet_Value(Transfer_Con.HID_CMD_SET_HW_SETTING,  0x00, 0x04);
                            tv_device_button_setting_kb_tvmode_manual_value.setText(getResources().getString(R.string.str_device_button_setting_kb_mobile));
                        }
                    }
                    else {
                        getIsHDMIOut();
                        tv_device_button_setting_kb_tvmode_auto_value.setText(getResources().getString(R.string.str_device_button_setting_kb_manual));
                        sw_device_button_setting_kb_tvmode.setEnabled(true);
                        tv_device_button_setting_kb_tvmode_manual_value.setEnabled(true);
                        layout_device_button_setting_kb_tvmode_resolution.setVisibility(View.VISIBLE);
                        if(sw_device_button_setting_kb_tvmode.isChecked()) {
                            mGlobalVar.tranSet_Value(Transfer_Con.HID_CMD_SET_HDMI_RESOLUTION, mGlobalVar.getManualHDMIWidth(), mGlobalVar.getManualHDMIHeight());
                            mGlobalVar.tranSet_Value(Transfer_Con.HID_CMD_SET_HW_SETTING, 0x04, 0x04);
                            tv_device_button_setting_kb_tvmode_manual_value.setText(getResources().getString(R.string.str_device_button_setting_kb_screen_projection));
                            mGlobalVar.setIsManualSetToHDMI(true);
                        }
                        else {
                            mGlobalVar.tranSet_Value(Transfer_Con.HID_CMD_SET_HW_SETTING, 0x00, 0x04);
                            tv_device_button_setting_kb_tvmode_manual_value.setText(getResources().getString(R.string.str_device_button_setting_kb_mobile));
                            mGlobalVar.setIsManualSetToHDMI(false);
                        }
                    }
                    //device_button_setting_kb_tvmode_manual_layout.setEnabled(!isChecked);

                    saveUserData(false);
                }
            });
            iv_device_button_setting_kb_btn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    final android.app.AlertDialog dialog;
                    android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(MainActivity.this);
                    View view = LayoutInflater.from(MainActivity.this).inflate(R.layout.device_button_setting_kb_img_gv_layout, null, false);
                    GridView gv_kb_function_select = view.findViewById(R.id.gv_device_button_setting_kb_img_gv);
                    final List<Map<String, Object>> data_list;
                    SimpleAdapter sim_adapter;
                    data_list = new ArrayList<Map<String, Object>>();
                    TypedArray ar = getResources().obtainTypedArray(R.array.mp1_button_images);
                    int len = ar.length();
                    int[] resIds = new int[len];

                    for(int a=4;a<mGlobalVar.getDirectCenterIndex();a++)
                    {
                        if((a>0x63)&&(a<0x80))
                            continue;
                        if((a==0x88)||(a==0x89))
                            continue;
                        if(mGlobalVar.getIsSupportMultiShotHelp_KB())
                        {
                            if((a>=0x3A)&&(a<=0x3E))
                            {
                                continue;
                            }
                        }
                        Map<String, Object> map = new HashMap<String, Object>();
                        resIds[a] = ar.getResourceId(a, 0);
                        map.put("image", resIds[a]);
                        map.put("id", a);
                        data_list.add(map);
                    }
                    String [] from ={"image"};
                    int [] to = {R.id.iv_kb_gv};
                    sim_adapter = new SimpleAdapter(MainActivity.this, data_list, R.layout.kb_function_select_gv_content, from, to);
                    gv_kb_function_select.setAdapter(sim_adapter);
                    builder.setView(view);
                    builder.setTitle(getResources().getString(R.string.str_global_fast_switch_mouse_and_key_selection));
                    dialog = builder.create();
                    dialog.show();
                    gv_kb_function_select.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                            dialog.dismiss();
                            int group,key;
                            int index = getItemID(data_list,position);
                            TypedArray ar = getResources().obtainTypedArray(R.array.mp1_button_images);
                            iv_device_button_setting_kb_btn.setImageResource(ar.getResourceId(index, 0));
                            ar.recycle();
                            if(index>=0x80)
                            {
                                if(index<0x88)
                                {
                                    group = 0;
                                    key = 1<<(index -0x80);
                                }
                                else
                                {
                                    group = 2;
                                    key = 1<<(index -0x8A);
                                }
                            }
                            else
                            {
                                group = 1;
                                key = index;
                            }
                            mGlobalVar.tranSet_Value_retry(Transfer_Con.HID_CMD_SET_MOUSE_SW_KEY,group,key,3);
                            mGlobalVar.tranSet_Value_retry(Transfer_Con.HID_CMD_SAVE_DATA, 0x00, 0x00,1);
                            //mGlobalVar.saveGameData_KB(mGlobalVar.curPkgName,mGlobalVar.curLabelName,mGlobalVar.coorTbl,mGlobalVar.attrTbl,mGlobalVar.attrEvTbl);
                            mGlobalVar.setSwitchToMouseKey_KB((group<<8)|key);
                            bIsSendMouseSwitchToDevice = true;
                            saveUserData(false);
                        }
                    });
                    ar.recycle();
                }
            });
            sb_device_button_setting_kb_rocker_range_value.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
                @Override
                public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                    tv_device_button_setting_kb_rocker_range_value.setText(String.format("%d%%",progress));
                    mGlobalVar.setRockerMoveRange_KB(progress);

                }

                @Override
                public void onStartTrackingTouch(SeekBar seekBar) {

                }

                @Override
                public void onStopTrackingTouch(SeekBar seekBar) {
                    mGlobalVar.tranSet_Value(Transfer_Con.HID_CMD_SET_ROCKER_RANGE,mGlobalVar.getRockerMoveRange_KB(),0);
                    saveUserData(false);
                }
            });

            sw_device_button_setting_kb_force_2touch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    if(isChecked)
                        mGlobalVar.tranSet_Value(Transfer_Con.HID_CMD_SET_HW_SETTING,  0x08, 0x08);
                    else
                        mGlobalVar.tranSet_Value(Transfer_Con.HID_CMD_SET_HW_SETTING,  0x00, 0x08);
                    mGlobalVar.setIsForceViewOut(isChecked);
                    saveUserData(false);
                }
            });

            sw_device_button_setting_kb_virtual_mouse.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    mGlobalVar.setIsUseVirtualMouse(isChecked);
                    saveUserData(false);
                }
            });

            sb_device_button_setting_kb_virtual_mouse_speed.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
                @Override
                public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                    tv_device_button_setting_kb_virtual_mouse_speed_value.setText(String.valueOf(progress));
                    mGlobalVar.setVirtualMouseInterval(progress);
                }

                @Override
                public void onStartTrackingTouch(SeekBar seekBar) {

                }

                @Override
                public void onStopTrackingTouch(SeekBar seekBar) {
                    mGlobalVar.tranSet_Value_retry(Transfer_Con.HID_CMD_SET_MOUSE_INTERVAL,  mGlobalVar.getVirtualMouseInterval(), 0x00,3);
                    saveUserData(false);
                }
            });

        } else {
            View view = LayoutInflater.from(MainActivity.this).inflate(R.layout.device_button_setting_layout, null, false);
            ImageView button = (ImageView) view.findViewById(R.id.iv_device_button_setting_back);
            Switch sw_device_button_setting_menu = view.findViewById(R.id.sw_device_button_setting_menu);
            Switch sw_device_button_setting_gyro = view.findViewById(R.id.sw_device_button_setting_gyro);
            LinearLayout device_button_setting_menu_layout = view.findViewById(R.id.device_button_setting_menu_layout);
            LinearLayout device_button_setting_gyro_layout = view.findViewById(R.id.device_button_setting_gyro_layout);

            LinearLayout device_button_setting_tvmode_layout = view.findViewById(R.id.device_button_setting_tvmode_layout);
            LinearLayout device_button_setting_posswap_layout = view.findViewById(R.id.device_button_setting_posswap_layout);
            LinearLayout device_button_setting_l3r3_layout = view.findViewById(R.id.device_button_setting_l3r3_layout);
            Switch sw_device_button_setting_tvmode = view.findViewById(R.id.sw_device_button_setting_tvmode);
            Switch sw_device_button_setting_powswap = view.findViewById(R.id.sw_device_button_setting_powswap);
            RadioButton rb_device_button_setting_cz = view.findViewById(R.id.rb_device_button_setting_cz);
            RadioButton rb_device_button_setting_l3r3 = view.findViewById(R.id.rb_device_button_setting_l3r3);


            if (mGlobalVar.getDeviceIndex() == Transfer_Con.DEVICE_HN1_INDEX)
                device_button_setting_menu_layout.setVisibility(View.VISIBLE);
            else
                device_button_setting_menu_layout.setVisibility(View.GONE);
            if (mGlobalVar.getDeviceIndex() == Transfer_Con.DEVICE_GM1_INDEX)
                device_button_setting_gyro_layout.setVisibility(View.VISIBLE);
            else
                device_button_setting_gyro_layout.setVisibility(View.GONE);

            if (mGlobalVar.getIsCurDeviceGamePad()) {
                if (mGlobalVar.get_IntVersion() >= ((1 << 24) + (1 << 8) + 21)) {
                    device_button_setting_tvmode_layout.setVisibility(View.VISIBLE);
                    device_button_setting_l3r3_layout.setVisibility(View.VISIBLE);
                    if (mGlobalVar.tranGet_Value((byte) (Transfer_Con.HID_CMD_RD_RESERVE), 2, 0, g_u8DataBuf)) {
                        if ((g_u8DataBuf[4] & 0x01) == 0x01) {
                            rb_device_button_setting_l3r3.setChecked(true);
                        } else {
                            rb_device_button_setting_cz.setChecked(true);
                        }
                        if ((g_u8DataBuf[4] & 0x02) == 0x02)
                            sw_device_button_setting_tvmode.setChecked(true);
                        else
                            sw_device_button_setting_tvmode.setChecked(false);

                        if ((mGlobalVar.get_IntVersion() >= ((1 << 24) + (1 << 8) + 23))&&(mGlobalVar.getDeviceIndex()==Transfer_Con.DEVICE_GM1_INDEX)) {
                            device_button_setting_posswap_layout.setVisibility(View.VISIBLE);
                            if ((g_u8DataBuf[4] & 0x04) == 0x04)
                                sw_device_button_setting_powswap.setChecked(true);
                            else
                                sw_device_button_setting_powswap.setChecked(false);
                        } else {
                            device_button_setting_posswap_layout.setVisibility(View.GONE);
                        }


                    }
                } else {
                    device_button_setting_tvmode_layout.setVisibility(View.GONE);
                    device_button_setting_l3r3_layout.setVisibility(View.GONE);
                    device_button_setting_posswap_layout.setVisibility(View.GONE);
                }
            } else {
                device_button_setting_tvmode_layout.setVisibility(View.GONE);
                device_button_setting_l3r3_layout.setVisibility(View.GONE);
                device_button_setting_posswap_layout.setVisibility(View.GONE);
            }

            if (mGlobalVar.tranGet_Value((byte) (Transfer_Con.HID_CMD_GET_HW_SETTING), 0xFF, 0xFF, g_u8DataBuf)) {
                if ((g_u8DataBuf[0] & 0x20) == 0x20)
                    sw_device_button_setting_menu.setChecked(true);
                else
                    sw_device_button_setting_menu.setChecked(false);

                if ((g_u8DataBuf[0] & 0x10) == 0x10)
                    sw_device_button_setting_gyro.setChecked(true);
                else
                    sw_device_button_setting_gyro.setChecked(false);
            }

            if (Transfer_Con.ENABLE_G_SENSOR_TEST && (mGlobalVar.getDeviceIndex() == Transfer_Con.DEVICE_GM1_INDEX)) {
                int data = 0;
                LinearLayout layout_g_sensor_test = view.findViewById(R.id.layout_g_sensor_sense);
                final SeekBar sb_g_sensor_y = view.findViewById(R.id.sb_g_sensor_y);
                final SeekBar sb_g_sensor_x = view.findViewById(R.id.sb_g_sensor_x);
                final TextView tv_g_sensor_test_value_y = view.findViewById(R.id.tv_g_sensor_test_value_y);
                final TextView tv_g_sensor_test_value_x = view.findViewById(R.id.tv_g_sensor_test_value_x);
                layout_g_sensor_test.setVisibility(View.VISIBLE);

                if (mGlobalVar.tranGet_Value(Transfer_Con.HID_CMD_RD_RESERVE, 3, data, g_u8DataBuf)) {
                    int x = (g_u8DataBuf[4] & 0xff) + ((g_u8DataBuf[5] & 0xff) << 8);
                    int y = (g_u8DataBuf[6] & 0xff) + ((g_u8DataBuf[7] & 0xff) << 8);
                    sb_g_sensor_y.setProgress(y);
                    sb_g_sensor_x.setProgress(x);
                    tv_g_sensor_test_value_y.setText(String.valueOf(y));
                    tv_g_sensor_test_value_x.setText(String.valueOf(x));
                }
                sb_g_sensor_y.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
                    @Override
                    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                        if ((progress == 0) || (progress > 1000))
                            return;
                        int val = (progress << 16) | sb_g_sensor_x.getProgress();
                        if (mGlobalVar.tranSet_Value(Transfer_Con.HID_CMD_WR_RESERVE, 3, val)) {
                            tv_g_sensor_test_value_y.setText(String.valueOf(progress));
                        }
                    }

                    @Override
                    public void onStartTrackingTouch(SeekBar seekBar) {

                    }

                    @Override
                    public void onStopTrackingTouch(SeekBar seekBar) {

                    }
                });
                sb_g_sensor_x.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
                    @Override
                    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                        if ((progress == 0) || (progress > 1000))
                            return;
                        int val = (sb_g_sensor_y.getProgress() << 16) | progress;
                        if (mGlobalVar.tranSet_Value(Transfer_Con.HID_CMD_WR_RESERVE, 3, val)) {
                            tv_g_sensor_test_value_x.setText(String.valueOf(progress));
                        }
                    }

                    @Override
                    public void onStartTrackingTouch(SeekBar seekBar) {

                    }

                    @Override
                    public void onStopTrackingTouch(SeekBar seekBar) {

                    }
                });
            }


            final PopupWindow popupWindow = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, true);
            popupWindow.setTouchable(true);
            popupWindow.setTouchInterceptor(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    return false;
                }
            });
            popupWindow.setBackgroundDrawable(new ColorDrawable(0xFFF8F8F8));
            //popupWindow.showAsDropDown(v);  //showAsDropDown(v,50,0);
            popupWindow.showAtLocation(view, Gravity.CENTER | Gravity.BOTTOM, 0, 0);

            button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    popupWindow.dismiss();
                }
            });
            sw_device_button_setting_menu.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    mGlobalVar.tranSet_Value((byte) (Transfer_Con.HID_CMD_SET_HW_SETTING), isChecked ? 0x20 : 0, 0x20);
                }
            });
            sw_device_button_setting_gyro.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    mGlobalVar.tranSet_Value((byte) (Transfer_Con.HID_CMD_SET_HW_SETTING), isChecked ? 0x10 : 0, 0x10);
                }
            });
            sw_device_button_setting_tvmode.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    if (mGlobalVar.tranGet_Value((byte) (Transfer_Con.HID_CMD_RD_RESERVE), 2, 0, g_u8DataBuf)) {
                        int data = (g_u8DataBuf[4] & 0xff) + ((g_u8DataBuf[5] & 0xff) << 8) + ((g_u8DataBuf[6] & 0xff) << 16) + ((g_u8DataBuf[7] & 0xff) << 24);
                        if (isChecked)
                            data |= 0x02;
                        else
                            data &= (~0x02);
                        mGlobalVar.tranSet_Value((byte) (Transfer_Con.HID_CMD_WR_RESERVE), 2, data);
                    }
                }
            });

            sw_device_button_setting_powswap.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    if (mGlobalVar.tranGet_Value((byte) (Transfer_Con.HID_CMD_RD_RESERVE), 2, 0, g_u8DataBuf)) {
                        int data = (g_u8DataBuf[4] & 0xff) + ((g_u8DataBuf[5] & 0xff) << 8) + ((g_u8DataBuf[6] & 0xff) << 16) + ((g_u8DataBuf[7] & 0xff) << 24);
                        if (isChecked)
                            data |= 0x04;
                        else
                            data &= (~0x04);
                        mGlobalVar.tranSet_Value((byte) (Transfer_Con.HID_CMD_WR_RESERVE), 2, data);
                    }
                }
            });

            rb_device_button_setting_cz.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    if (mGlobalVar.tranGet_Value((byte) (Transfer_Con.HID_CMD_RD_RESERVE), 2, 0, g_u8DataBuf)) {
                        int data = (g_u8DataBuf[4] & 0xff) + ((g_u8DataBuf[5] & 0xff) << 8) + ((g_u8DataBuf[6] & 0xff) << 16) + ((g_u8DataBuf[7] & 0xff) << 24);
                        if (isChecked)
                            data &= (~0x01);
                        else
                            data |= 0x01;
                        mGlobalVar.tranSet_Value((byte) (Transfer_Con.HID_CMD_WR_RESERVE), 2, data);
                    }
                }
            });
            rb_device_button_setting_l3r3.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    if (mGlobalVar.tranGet_Value((byte) (Transfer_Con.HID_CMD_RD_RESERVE), 2, 0, g_u8DataBuf)) {
                        int data = (g_u8DataBuf[4] & 0xff) + ((g_u8DataBuf[5] & 0xff) << 8) + ((g_u8DataBuf[6] & 0xff) << 16) + ((g_u8DataBuf[7] & 0xff) << 24);
                        if (isChecked)
                            data |= 0x01;
                        else
                            data &= (~0x01);
                        mGlobalVar.tranSet_Value((byte) (Transfer_Con.HID_CMD_WR_RESERVE), 2, data);
                    }
                }
            });
        }
    }





    void showDeviceButtonSetting_new() {
        if (mGlobalVar.getIsLastConDeviceKB()) {
            device_button_setting_menu_layout.setVisibility(View.GONE);
            device_button_setting_gyro_layout.setVisibility(View.GONE);
            layout_g_sensor_sense.setVisibility(View.GONE);
            device_button_setting_tvmode_layout.setVisibility(View.GONE);
            device_button_setting_posswap_layout.setVisibility(View.GONE);
            device_button_setting_l3r3_layout.setVisibility(View.GONE);
            device_button_setting_brake_gas_layout.setVisibility(View.GONE);
            device_button_setting_rocker_setting_swap_layout.setVisibility(View.GONE);
            device_button_setting_rocker_setting_r_rock_range.setVisibility(View.GONE);
            device_button_setting_rocker_setting_sense_layout.setVisibility(View.GONE);


            device_button_setting_kb_switch_to_mouse_layout.setVisibility(View.VISIBLE);

            if(mGlobalVar.getDeviceIndex()==Transfer_Con.DEVICE_BX2_INDEX) {
                device_button_setting_kb_audio_layout.setVisibility(View.VISIBLE);
                cb_device_button_setting_kb_audio.setChecked(mGlobalVar.getIsAudioOut());
            }
            if(mGlobalVar.getbIsUsbConnect()&&mGlobalVar.getbIsTransferMode())
            {
                sw_device_button_setting_kb_tvmode.setEnabled(true);
                sw_device_button_setting_kb_tvmode_auto.setEnabled(true);
                sw_device_button_setting_kb_force_2touch.setEnabled(true);
                sw_device_button_setting_kb_virtual_mouse.setEnabled(true);
                sb_device_button_setting_kb_rocker_range_value.setEnabled(true);
                sb_device_button_setting_kb_virtual_mouse_speed.setEnabled(true);

                et_device_button_setting_kb_width.setEnabled(true);
                et_device_button_setting_kb_height.setEnabled(true);
                iv_device_button_setting_kb_btn.setEnabled(true);
                cb_device_button_setting_kb_audio.setEnabled(true);
            }
            else
            {
                sw_device_button_setting_kb_tvmode.setEnabled(false);
                sw_device_button_setting_kb_tvmode_auto.setEnabled(false);
                sw_device_button_setting_kb_force_2touch.setEnabled(false);
                sw_device_button_setting_kb_virtual_mouse.setEnabled(false);
                sb_device_button_setting_kb_rocker_range_value.setEnabled(false);
                sb_device_button_setting_kb_virtual_mouse_speed.setEnabled(false);

                et_device_button_setting_kb_width.setEnabled(false);
                et_device_button_setting_kb_height.setEnabled(false);
                iv_device_button_setting_kb_btn.setEnabled(false);
                cb_device_button_setting_kb_audio.setEnabled(false);
            }

            if(Transfer_Con.ENABLE_MANUAL_TV_SWITCH) {
                if (mGlobalVar.getIsSupportSwitchTVMode_KB()) {
                    device_button_setting_kb_tvmode_layout.setVisibility(View.VISIBLE);
                } else {
                    device_button_setting_kb_tvmode_layout.setVisibility(View.GONE);
                }
            }

            if(mGlobalVar.getIsSupportMouseSideKeyAndHorSense())
            {
                layout_device_button_setting_kb_switch_to_mouse.setVisibility(View.VISIBLE);
                if(mGlobalVar.tranGet_Value_retry(Transfer_Con.HID_CMD_GET_MOUSE_SW_KEY,0,0,g_u8DataBuf,5))
                {
                    TypedArray ar;
                    int index;

                    mGlobalVar.setSwitchToMouseKey_KB(((g_u8DataBuf[0]&0xff)<<8)|(g_u8DataBuf[4]&0xff));
                    cb_device_button_setting_kb_switch_to_mouse_press.setChecked((g_u8DataBuf[0]&0x80)==0x80);
                    ar = getResources().obtainTypedArray(R.array.mp1_button_images);
                    index = mGlobalVar.switchMouseToKeyEvent(g_u8DataBuf[0]&0xff,g_u8DataBuf[4]&0xff);
                    iv_device_button_setting_kb_btn.setImageResource(ar.getResourceId(index, 0));
                    ar.recycle();
                }
            }
            else
            {
                layout_device_button_setting_kb_switch_to_mouse.setVisibility(View.GONE);
            }

            if(mGlobalVar.tranGet_Value_retry(Transfer_Con.HID_CMD_GET_HW_SETTING,0,0xFF,g_u8DataBuf,5))
            {
                if((g_u8DataBuf[0]&0x04)==0x04)
                {
                    sw_device_button_setting_kb_tvmode.setChecked(true);
                    tv_device_button_setting_kb_tvmode_manual_value.setText(getResources().getString(R.string.str_device_button_setting_kb_screen_projection));
                }
                else
                {
                    sw_device_button_setting_kb_tvmode.setChecked(false);
                    tv_device_button_setting_kb_tvmode_manual_value.setText(getResources().getString(R.string.str_device_button_setting_kb_mobile));
                }
                //Toast.makeText(MainActivity.this,String.format("0x%x,0x%x,0x%x,0x%x",g_u8DataBuf[0],g_u8DataBuf[1],g_u8DataBuf[2],g_u8DataBuf[3]),Toast.LENGTH_SHORT).show();
            }
            if(mGlobalVar.getIsCurDeviceKBBox()) {
                getIsHDMIOut();
                if (mGlobalVar.getIsAutoSwitchToHDMI()) {
                    device_button_setting_kb_tvmode_manual_layout.setEnabled(false);
                    sw_device_button_setting_kb_tvmode_auto.setChecked(true);
                    tv_device_button_setting_kb_tvmode_auto_value.setText(getResources().getString(R.string.str_device_button_setting_kb_auto));
                    tv_device_button_setting_kb_tvmode_manual_value.setEnabled(false);
                    sw_device_button_setting_kb_tvmode.setEnabled(false);
                    layout_device_button_setting_kb_tvmode_resolution.setVisibility(View.GONE);
                    if (bIsDetectHDMIIn) {
                        sw_device_button_setting_kb_tvmode.setChecked(true);
                        tv_device_button_setting_kb_tvmode_manual_value.setText(getResources().getString(R.string.str_device_button_setting_kb_screen_projection));
                        if ((g_u8DataBuf[0] & 0x04) != 0x04)
                            mGlobalVar.tranSet_Value(Transfer_Con.HID_CMD_SET_HW_SETTING, 0x04, 0x04);
                    } else {
                        sw_device_button_setting_kb_tvmode.setChecked(false);
                        tv_device_button_setting_kb_tvmode_manual_value.setText(getResources().getString(R.string.str_device_button_setting_kb_mobile));
                        if ((g_u8DataBuf[0] & 0x04) == 0x04)
                            mGlobalVar.tranSet_Value(Transfer_Con.HID_CMD_SET_HW_SETTING, 0x00, 0x04);
                    }
                } else {
                    device_button_setting_kb_tvmode_manual_layout.setEnabled(true);
                    sw_device_button_setting_kb_tvmode_auto.setChecked(false);
                    layout_device_button_setting_kb_tvmode_resolution.setVisibility(View.VISIBLE);
                    tv_device_button_setting_kb_tvmode_auto_value.setText(getResources().getString(R.string.str_device_button_setting_kb_manual));
                    if ((g_u8DataBuf[0] & 0x04) == 0x04)
                    {
                        sw_device_button_setting_kb_tvmode.setChecked(true);
                        tv_device_button_setting_kb_tvmode_manual_value.setText(getResources().getString(R.string.str_device_button_setting_kb_screen_projection));
                        mGlobalVar.setIsManualSetToHDMI(true);
                    }
                    else
                    {
                        sw_device_button_setting_kb_tvmode.setChecked(false);
                        tv_device_button_setting_kb_tvmode_manual_value.setText(getResources().getString(R.string.str_device_button_setting_kb_mobile));
                        mGlobalVar.setIsManualSetToHDMI(false);
                    }

                }
                et_device_button_setting_kb_width.setKeyListener(DigitsKeyListener.getInstance("1234567890"));
                et_device_button_setting_kb_height.setKeyListener(DigitsKeyListener.getInstance("1234567890"));
                et_device_button_setting_kb_width.setHint(String.valueOf(mGlobalVar.getManualHDMIWidth()));
                et_device_button_setting_kb_height.setHint(String.valueOf(mGlobalVar.getManualHDMIHeight()));
                if(bIsDetectHDMIIn)
                    tv_device_button_setting_kb_tvmode_resolution.setText(String.format((getResources().getString(R.string.str_device_button_setting_resolution_of_display)+"%dX%d"),local_width,local_height));
                else
                    tv_device_button_setting_kb_tvmode_resolution.setText(String.format((getResources().getString(R.string.str_device_button_setting_monitor_not_connected))));
            }
            if(mGlobalVar.getIsSupportMultiShotHelp_KB())
            {
                device_button_setting_kb_rocker_range_layout.setVisibility(View.VISIBLE);
                sb_device_button_setting_kb_rocker_range_value.setProgress(mGlobalVar.getRockerMoveRange_KB());
                tv_device_button_setting_kb_rocker_range_value.setText(String.format("%d%%",mGlobalVar.getRockerMoveRange_KB()));

                device_button_setting_kb_force_2touch_layout.setVisibility(View.VISIBLE);
                sw_device_button_setting_kb_force_2touch.setChecked(mGlobalVar.getIsForceViewOut());
            }

            if(mGlobalVar.getIsSupportVirtualMouse_KB())
            {
                device_button_setting_kb_virtual_mouse_layout.setVisibility(View.VISIBLE);
                sw_device_button_setting_kb_virtual_mouse.setChecked(mGlobalVar.getIsUseVirtualMouse());
                if(Transfer_Con.ENABLE_VIRTUAL_MOUSE_SPEED)
                {
                    //device_button_setting_kb_virtual_mouse_speed_layout.setVisibility(View.VISIBLE);
                    sb_device_button_setting_kb_virtual_mouse_speed.setProgress(mGlobalVar.getVirtualMouseInterval());
                    tv_device_button_setting_kb_virtual_mouse_speed_value.setText(String.valueOf(mGlobalVar.getVirtualMouseInterval()));
                }
            }
            if(mGlobalVar.getIsSupportMousePressSwitch_KB())
            {
                cb_device_button_setting_kb_switch_to_mouse_press.setVisibility(View.VISIBLE);
            }



        } else if(mGlobalVar.getIsLastConDeviceGamePad()){

            device_button_setting_kb_tvmode_layout.setVisibility(View.GONE);
            device_button_setting_kb_force_2touch_layout.setVisibility(View.GONE);
            device_button_setting_kb_virtual_mouse_layout.setVisibility(View.GONE);
            device_button_setting_kb_rocker_range_layout.setVisibility(View.GONE);
            device_button_setting_kb_switch_to_mouse_layout.setVisibility(View.GONE);
            device_button_setting_kb_audio_layout.setVisibility(View.GONE);


            if(mGlobalVar.getbIsUsbConnect()&&mGlobalVar.getbIsTransferMode())
            {
                sw_device_button_setting_menu.setEnabled(true);
                sw_device_button_setting_gyro.setEnabled(true);
                sw_device_button_setting_tvmode.setEnabled(true);
                sw_device_button_setting_powswap.setEnabled(true);
                rb_device_button_setting_cz.setEnabled(true);
                rb_device_button_setting_l3r3.setEnabled(true);
                sb_g_sensor_y.setEnabled(true);
                sb_g_sensor_x.setEnabled(true);
            }
            else
            {
                sw_device_button_setting_menu.setEnabled(false);
                sw_device_button_setting_gyro.setEnabled(false);
                sw_device_button_setting_tvmode.setEnabled(false);
                sw_device_button_setting_powswap.setEnabled(false);
                rb_device_button_setting_cz.setEnabled(false);
                rb_device_button_setting_l3r3.setEnabled(false);
                sb_g_sensor_y.setEnabled(false);
                sb_g_sensor_x.setEnabled(false);
            }

            if (mGlobalVar.getDeviceIndex() == Transfer_Con.DEVICE_HN1_INDEX)
                device_button_setting_menu_layout.setVisibility(View.VISIBLE);
            else
                device_button_setting_menu_layout.setVisibility(View.GONE);
            if (mGlobalVar.getDeviceIndex() == Transfer_Con.DEVICE_GM1_INDEX)
                device_button_setting_gyro_layout.setVisibility(View.VISIBLE);
            else
                device_button_setting_gyro_layout.setVisibility(View.GONE);

            if (mGlobalVar.getIsCurDeviceGamePad()) {
                device_button_setting_rocker_setting_sense_layout.setVisibility(View.VISIBLE);
                if (mGlobalVar.get_IntVersion() >= ((1 << 24) + (1 << 8) + 21)) {
                    device_button_setting_tvmode_layout.setVisibility(View.VISIBLE);
                    device_button_setting_l3r3_layout.setVisibility(View.VISIBLE);
                    if(mGlobalVar.get_IntVersion() >= ((1 << 24) + (1 << 8) + 26))
                        device_button_setting_brake_gas_layout.setVisibility(View.VISIBLE);
                    if (mGlobalVar.tranGet_Value((byte) (Transfer_Con.HID_CMD_RD_RESERVE), 2, 0, g_u8DataBuf)) {
                        if ((g_u8DataBuf[4] & 0x01) == 0x01) {
                            rb_device_button_setting_l3r3.setChecked(true);
                        } else {
                            rb_device_button_setting_cz.setChecked(true);
                        }
                        if ((g_u8DataBuf[4] & 0x02) == 0x02)
                            sw_device_button_setting_tvmode.setChecked(true);
                        else
                            sw_device_button_setting_tvmode.setChecked(false);

                        if ((mGlobalVar.get_IntVersion() >= ((1 << 24) + (1 << 8) + 23))&&(mGlobalVar.getDeviceIndex()==Transfer_Con.DEVICE_GM1_INDEX)) {
                            device_button_setting_posswap_layout.setVisibility(View.VISIBLE);
                            if ((g_u8DataBuf[4] & 0x04) == 0x04)
                                sw_device_button_setting_powswap.setChecked(true);
                            else
                                sw_device_button_setting_powswap.setChecked(false);
                        } else {
                            device_button_setting_posswap_layout.setVisibility(View.GONE);
                        }

                        if ((g_u8DataBuf[4] & 0x08) == 0x08)
                            cb_device_button_setting_brake_gas.setChecked(true);
                        else
                            cb_device_button_setting_brake_gas.setChecked(false);
                    }
                } else {
                    device_button_setting_tvmode_layout.setVisibility(View.GONE);
                    device_button_setting_l3r3_layout.setVisibility(View.GONE);
                    device_button_setting_posswap_layout.setVisibility(View.GONE);
                }
            } else {
                device_button_setting_tvmode_layout.setVisibility(View.GONE);
                device_button_setting_l3r3_layout.setVisibility(View.GONE);
                device_button_setting_posswap_layout.setVisibility(View.GONE);
                device_button_setting_brake_gas_layout.setVisibility(View.GONE);
                device_button_setting_rocker_setting_sense_layout.setVisibility(View.GONE);
            }

            if (mGlobalVar.tranGet_Value((byte) (Transfer_Con.HID_CMD_GET_HW_SETTING), 0xFF, 0xFF, g_u8DataBuf)) {
                if ((g_u8DataBuf[0] & 0x20) == 0x20)
                    sw_device_button_setting_menu.setChecked(true);
                else
                    sw_device_button_setting_menu.setChecked(false);

                if ((g_u8DataBuf[0] & 0x10) == 0x10)
                    sw_device_button_setting_gyro.setChecked(true);
                else
                    sw_device_button_setting_gyro.setChecked(false);
            }

            if (Transfer_Con.ENABLE_G_SENSOR_TEST && (mGlobalVar.getDeviceIndex() == Transfer_Con.DEVICE_GM1_INDEX)) {
                int data = 0;

                layout_g_sensor_sense.setVisibility(View.VISIBLE);

                if (mGlobalVar.tranGet_Value(Transfer_Con.HID_CMD_RD_RESERVE, 3, data, g_u8DataBuf)) {
                    int x = (g_u8DataBuf[4] & 0xff) + ((g_u8DataBuf[5] & 0xff) << 8);
                    int y = (g_u8DataBuf[6] & 0xff) + ((g_u8DataBuf[7] & 0xff) << 8);
                    sb_g_sensor_y.setProgress(y);
                    sb_g_sensor_x.setProgress(x);
                    tv_g_sensor_test_value_y.setText(String.valueOf(y));
                    tv_g_sensor_test_value_x.setText(String.valueOf(x));
                }
            }

            if(mGlobalVar.getIsSupportMenuKey())
            {
                device_button_setting_rocker_setting_swap_layout.setVisibility(View.VISIBLE);
            }

            if((mGlobalVar.getDeviceIndex()==Transfer_Con.DEVICE_GM1_INDEX)||(mGlobalVar.getDeviceIndex()==Transfer_Con.DEVICE_HN2_INDEX)||((mGlobalVar.getDeviceIndex()==Transfer_Con.DEVICE_HN1_INDEX)&&(mGlobalVar.get_IntVersion()>(mGlobalVar.SUPPORT_MENU_KEY_VER+1))))
            {
                device_button_setting_rocker_setting_r_rock_range.setVisibility(View.VISIBLE);
            }

            if((mGlobalVar.getDeviceIndex()==Transfer_Con.DEVICE_HN1_INDEX)||(mGlobalVar.getDeviceIndex()==Transfer_Con.DEVICE_HN2_INDEX))
            {
                if(mGlobalVar.get_IntVersion()>=((1<<24)+(1<<8)+19)) {
                    device_button_setting_rocker_setting_left_ups.setVisibility(View.VISIBLE);
                    device_button_setting_rocker_setting_left_range.setVisibility(View.VISIBLE);
                }
            }
            if((mGlobalVar.getDeviceIndex()==Transfer_Con.DEVICE_GM1_INDEX))
            {
                if(mGlobalVar.get_IntVersion()>=((1<<24)+(1<<8)+19)) {
                    device_button_setting_rocker_setting_left_ups.setVisibility(View.VISIBLE);
                    device_button_setting_rocker_setting_left_range.setVisibility(View.VISIBLE);
                }
            }

            if(mGlobalVar.tranGet_Value((byte)(Transfer_Con.HID_CMD_GET_R_ROCK_MIN),0,0,g_u8DataBuf))
            {
                sb_rocker_setting_min.setProgress(g_u8DataBuf[0]);
                tv_rocker_setting_min_value.setText(String.valueOf((g_u8DataBuf[0]-2)*100/(sb_rocker_setting_min.getMax()-2))+"%");
            }
            if(mGlobalVar.tranGet_Value((byte)(Transfer_Con.HID_CMD_GET_R_ROCK_MAX),0,0,g_u8DataBuf))
            {
                sb_rocker_setting_max.setProgress(g_u8DataBuf[0]);
                tv_rocker_setting_max_value.setText(String.valueOf((g_u8DataBuf[0]-20)*100/(sb_rocker_setting_max.getMax()-20))+"%");
            }
            if(mGlobalVar.tranGet_Value((byte)(Transfer_Con.HID_CMD_GET_R_ROCK_TIME),0,0,g_u8DataBuf))
            {
                sb_rocker_setting_time.setProgress(g_u8DataBuf[0]);
                tv_rocker_setting_time_value.setText(String.valueOf((g_u8DataBuf[0]-1)*100/(sb_rocker_setting_time.getMax()-1))+"%");
            }
            if(mGlobalVar.tranGet_Value((byte)(Transfer_Con.HID_CMD_GET_LEFT_VSEN),0,0,g_u8DataBuf))
            {
                sb_rocker_setting_left_range.setProgress(g_u8DataBuf[0]);
                tv_rocker_setting_left_range.setText(String.valueOf(g_u8DataBuf[0]*100/sb_rocker_setting_left_range.getMax())+"%");
            }
            if(mGlobalVar.tranGet_Value((byte)(Transfer_Con.HID_CMD_GET_HW_SETTING),0xFF,0xFF,g_u8DataBuf))
            {
                if((g_u8DataBuf[0]&0x40)==0x40)
                {
                    ckb_rocker_setting_swap.setChecked(true);
                    bIsSwapChecked = true;
                }
                else
                {
                    ckb_rocker_setting_swap.setChecked(false);
                    bIsSwapChecked = false;
                }
                if((g_u8DataBuf[0]&0x08)==0x08)
                    rb_rocker_setting_r_rocker_range_limited.setChecked(true);
                else
                    rb_rocker_setting_r_rocker_range_full.setChecked(true);

                if((g_u8DataBuf[0]&0x02)==0x02)
                    ckb_rocker_setting_left_ups.setChecked(true);
                else
                    ckb_rocker_setting_left_ups.setChecked(false);
            }
        }
        else
        {
            device_button_setting_kb_tvmode_layout.setVisibility(View.GONE);
            device_button_setting_kb_force_2touch_layout.setVisibility(View.GONE);
            device_button_setting_kb_virtual_mouse_layout.setVisibility(View.GONE);
            device_button_setting_kb_rocker_range_layout.setVisibility(View.GONE);
            device_button_setting_kb_switch_to_mouse_layout.setVisibility(View.GONE);
            device_button_setting_kb_audio_layout.setVisibility(View.GONE);
            device_button_setting_menu_layout.setVisibility(View.GONE);
            device_button_setting_gyro_layout.setVisibility(View.GONE);
            layout_g_sensor_sense.setVisibility(View.GONE);
            device_button_setting_tvmode_layout.setVisibility(View.GONE);
            device_button_setting_posswap_layout.setVisibility(View.GONE);
            device_button_setting_l3r3_layout.setVisibility(View.GONE);
            device_button_setting_brake_gas_layout.setVisibility(View.GONE);
            device_button_setting_rocker_setting_swap_layout.setVisibility(View.GONE);
            device_button_setting_rocker_setting_r_rock_range.setVisibility(View.GONE);
            device_button_setting_rocker_setting_sense_layout.setVisibility(View.GONE);
        }
    }




    void showDataSetting()
    {
        View view = LayoutInflater.from(MainActivity.this).inflate(R.layout.device_data_layout,null,false);
        ImageView button = (ImageView)view.findViewById(R.id.iv_device_data_back);
        RelativeLayout ll_device_data_pos_load = (RelativeLayout) view.findViewById(R.id.ll_device_data_pos_load);
        RelativeLayout ll_device_data_pos_save = (RelativeLayout) view.findViewById(R.id.ll_device_data_pos_save);

        RelativeLayout rl_device_data_attr_load = (RelativeLayout) view.findViewById(R.id.rl_device_data_attr_load);
        RelativeLayout rl_device_data_attr_save = (RelativeLayout) view.findViewById(R.id.rl_device_data_attr_save);

        LinearLayout device_data_key_advance_layout =  view.findViewById(R.id.device_data_key_advance_layout);

        if(mGlobalVar.getIsLastConDeviceGamePad())
        {
            device_data_key_advance_layout.setVisibility(View.VISIBLE);
        }

        final PopupWindow popupWindow = new PopupWindow(view,ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.MATCH_PARENT,true);
        popupWindow.setTouchable(true);
        popupWindow.setTouchInterceptor(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return false;
            }
        });
        popupWindow.setBackgroundDrawable(new ColorDrawable(0xFFF8F8F8));
        //popupWindow.showAsDropDown(v);  //showAsDropDown(v,50,0);
        popupWindow.showAtLocation(view,Gravity.CENTER|Gravity.BOTTOM,0,0);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });
        ll_device_data_pos_save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (mGlobalVar.getIsLastConDeviceKB()) {
                    AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                    final EditText editText = new EditText(MainActivity.this);
                    editText.setHint("Game1_Data");
                    editText.setSingleLine();
                    builder.setTitle(getResources().getString(R.string.string_pop_data_save_dialog_filename))
                            .setView(editText)
                            .setMessage(getResources().getString(R.string.string_pop_data_save_dialog_input_filename))
                            .setPositiveButton(getResources().getString(R.string.string_pop_confirm), new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {

                                    String strFileName = "Game1_Data";

                                    if (!android.text.TextUtils.isEmpty(editText.getText()))
                                        strFileName = editText.getText().toString();
                                    mGlobalVar.getCoordinateFromDevice_KB();
                                    mGlobalVar.getAttributeFromDevice_KB();
                                    mGlobalVar.getAttributeEventTableFromDevice_KB();
                                    JSONArray jsonArray = new JSONArray();
                                    for (int data : mGlobalVar.coorTbl) {
                                        jsonArray.put(data);
                                    }
                                    for(int [] array : mGlobalVar.attrTbl) {
                                        for (int data : array) {
                                            jsonArray.put(data);
                                        }
                                    }
                                    for (int data : mGlobalVar.attrEvTbl) {
                                        jsonArray.put(data);
                                    }

                                    if (Build.VERSION.SDK_INT >= 26 && checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                                            != PackageManager.PERMISSION_GRANTED) {
                                        requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
                                    } else {
                                        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {

                                            String fileName = strFileName + ".caf";
                                            String fileContent = jsonArray.toString();
                                            //得到指定文件的输出流
                                            String sdPath = Environment.getExternalStorageDirectory().getAbsolutePath();
                                            File file = new File(sdPath + LOCAL_PATH);
                                            if (!file.exists()) {
                                                if (file.mkdirs())//;//创建文件夹
                                                {
                                                    Log.d(TAG, "创建成功");
                                                } else {
                                                    Log.d(TAG, "创建失败");
                                                }
                                            }
                                            String filePath = sdPath + LOCAL_PATH + "/" + fileName;
                                            String filesPath = getExternalFilesDir(null).getAbsolutePath();
                                            System.out.println(filesPath);
                                            FileOutputStream fos = null;
                                            try {
                                                fos = new FileOutputStream(filePath);
                                                fos.write(fileContent.getBytes("utf-8"));
                                                fos.close();
                                            } catch (FileNotFoundException e) {
                                                e.printStackTrace();
                                            } catch (UnsupportedEncodingException e) {
                                                e.printStackTrace();
                                            } catch (IOException e) {
                                                e.printStackTrace();
                                            }
                                            Toast.makeText(MainActivity.this, getResources().getString(R.string.string_pop_file_save_success) + filePath, Toast.LENGTH_SHORT).show();
                                        } else {
                                            Toast.makeText(MainActivity.this, getResources().getString(R.string.string_pop_file_save_fail), Toast.LENGTH_SHORT).show();
                                        }
                                    }
                                }
                            }).create().show();
                } else {
                    AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                    final EditText editText = new EditText(MainActivity.this);
                    editText.setHint("SOE_Coor_TBL");
                    editText.setSingleLine();
                    builder.setTitle(getResources().getString(R.string.string_pop_data_save_dialog_filename))
                            .setView(editText)
                            .setMessage(getResources().getString(R.string.string_pop_data_save_dialog_input_filename))
                            .setPositiveButton(getResources().getString(R.string.string_pop_confirm), new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {

                                    String strFileName = "SOE_Coor_TBL";

                                    if (!android.text.TextUtils.isEmpty(editText.getText()))
                                        strFileName = editText.getText().toString();

                                    String str = "";
                                    boolean bFlag = false;
                                    JSONArray saveArray = new JSONArray();
                                    for (int game = 0; game < mGlobalVar.getGameGpTotalNum(); game++) {
                                        for (int phone = 0; phone < 8; phone++) {
                                            if (mGlobalVar.getIsPtExit(phone, game)) {
                                                bFlag = true;
                                                mGlobalVar.loadCoordinateTable(phone, game);
                                                ptTbl = mGlobalVar.getPTTable();

                                                JSONArray jsonArray = new JSONArray();
                                                jsonArray.put(phone);
                                                jsonArray.put(game);
                                                if (game >= Transfer_Con.MAX_GP_FIX_GAME_NUM) {
                                                    jsonArray.put(mGlobalVar.getPackageName(game));
                                                    jsonArray.put(mGlobalVar.getUserGameName(game - Transfer_Con.MAX_GP_FIX_GAME_NUM));
                                                } else {
                                                    jsonArray.put(Transfer_Con.defPackageName[game]);
                                                    jsonArray.put(Transfer_Con.GameName[game]);
                                                }
                                                for (int data : ptTbl) {
                                                    jsonArray.put(data);
                                                }
                                                saveArray.put(jsonArray);
                                            }
                                        }
                                    }
                                    if (bFlag) {
                                        if (Build.VERSION.SDK_INT >= 26 && checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                                                != PackageManager.PERMISSION_GRANTED) {
                                            requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
                                        } else {
                                            if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {

                                                String fileName = strFileName + ".cor";
                                                String fileContent = saveArray.toString();
                                                //得到指定文件的输出流
                                                String sdPath = Environment.getExternalStorageDirectory().getAbsolutePath();
                                                File file = new File(sdPath + LOCAL_PATH);
                                                if (!file.exists()) {
                                                    if (file.mkdirs())//;//创建文件夹
                                                    {
                                                        Log.d(TAG, "创建成功");
                                                    } else {
                                                        Log.d(TAG, "创建失败");
                                                    }
                                                }
                                                String filePath = sdPath + LOCAL_PATH + "/" + fileName;
                                                String filesPath = getExternalFilesDir(null).getAbsolutePath();
                                                System.out.println(filesPath);
                                                FileOutputStream fos = null;
                                                try {
                                                    fos = new FileOutputStream(filePath);
                                                    fos.write(fileContent.getBytes("utf-8"));
                                                    fos.close();
                                                } catch (FileNotFoundException e) {
                                                    e.printStackTrace();
                                                } catch (UnsupportedEncodingException e) {
                                                    e.printStackTrace();
                                                } catch (IOException e) {
                                                    e.printStackTrace();
                                                }
                                                Toast.makeText(MainActivity.this, getResources().getString(R.string.string_pop_file_save_success) + filePath, Toast.LENGTH_SHORT).show();
                                            } else {
                                                Toast.makeText(MainActivity.this, getResources().getString(R.string.string_pop_file_save_fail), Toast.LENGTH_SHORT).show();
                                            }
                                        }
                                    }

                                }
                            }).create().show();
                }
            }
        });

        ll_device_data_pos_load.setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View v) {

               if (Build.VERSION.SDK_INT >= 26 && checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                       != PackageManager.PERMISSION_GRANTED) {
                   requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
               } else {

                   if (mGlobalVar.getIsLastConDeviceKB()) {
                       ArrayList<String> fileList = getFileList("caf");
                       final String[] item = new String[fileList.size()];
                       for (int a = 0; a < fileList.size(); a++)
                           item[a] = fileList.get(a);

                       AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                       builder.setTitle(getResources().getString(R.string.string_pop_data_load_select_filename))
                               .setItems(item, new DialogInterface.OnClickListener() {
                                   @Override
                                   public void onClick(DialogInterface dialog, int which) {
                                       //Toast.makeText(MainActivity.this,String.valueOf(which),Toast.LENGTH_SHORT).show();
                                       String fileName = item[which];
                                       if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                                           Log.d(TAG, "Load");
                                           String sdPath = Environment.getExternalStorageDirectory().getAbsolutePath();
                                           String filePath = sdPath + LOCAL_PATH + "/" + fileName;
                                           FileInputStream fis = null;
                                           String content = null;
                                           try {
                                               fis = new FileInputStream(filePath);
                                               ByteArrayOutputStream baos = new ByteArrayOutputStream();
                                               byte[] buffer = new byte[1024];
                                               int len = -1;
                                               while ((len = fis.read(buffer)) != -1) {
                                                   baos.write(buffer, 0, len);
                                               }
                                               content = baos.toString();
                                               fis.close();
                                           } catch (FileNotFoundException e) {
                                               e.printStackTrace();
                                           } catch (IOException e) {
                                               e.printStackTrace();
                                           }

                                           try {
                                               JSONArray jsonArray = new JSONArray(content);
                                               if(jsonArray.length()<=0)
                                                   return;

                                               for(int a=0;a<Transfer_Con.MAX_COORDINATE*2;a++)
                                               {
                                                   mGlobalVar.coorTbl[a] = jsonArray.getInt(a);
                                               }
                                               for(int a=0;a<Transfer_Con.MAX_COORDINATE;a++)
                                               {
                                                   for(int i=0;i<3;i++)
                                                   {
                                                       mGlobalVar.attrTbl[a][i] = jsonArray.getInt(Transfer_Con.MAX_COORDINATE*2+a*3+i);
                                                   }
                                               }

                                               if(jsonArray.length()>=(3+Transfer_Con.MAX_COORDINATE*5+Transfer_Con.MAX_AUTOEVENT_LENGTH_KB))
                                               {
                                                   for(int a=0;a<Transfer_Con.MAX_AUTOEVENT_LENGTH_KB;a++)    // coordinate
                                                   {
                                                       mGlobalVar.attrEvTbl[a] = jsonArray.getInt(3+Transfer_Con.MAX_COORDINATE*5+a);
                                                   }
                                               }
                                               else
                                               {
                                                   for(int a=0;a<Transfer_Con.MAX_AUTOEVENT_LENGTH_KB;a++)    // coordinate
                                                   {
                                                       mGlobalVar.attrEvTbl[a] = 0;
                                                   }
                                               }

                                           } catch (JSONException e) {
                                               e.printStackTrace();
                                           }

                                           mGlobalVar.sendCoordinateToDevice_KB();
                                           mGlobalVar.sendAttributeToDevice_KB();
                                           mGlobalVar.sendAttributeEventTableToDevice_KB();
                                           //mGlobalVar.sendLocalSettingToDevice();
                                           Toast.makeText(MainActivity.this, getResources().getString(R.string.string_pop_file_load_success) + content, Toast.LENGTH_SHORT).show();
                                       } else {
                                           Toast.makeText(MainActivity.this, getResources().getString(R.string.string_pop_file_load_fail), Toast.LENGTH_SHORT).show();
                                       }
                                   }

                               }).create().show();
                   }
                    else
                   {
                   ArrayList<String> fileList = getFileList("cor");
                   final String[] item = new String[fileList.size()];
                   for (int a = 0; a < fileList.size(); a++)
                       item[a] = fileList.get(a);

                   AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                   builder.setTitle(getResources().getString(R.string.string_pop_data_load_select_filename))
                           .setItems(item, new DialogInterface.OnClickListener() {
                               @Override
                               public void onClick(DialogInterface dialog, int which) {
                                   //Toast.makeText(MainActivity.this,String.valueOf(which),Toast.LENGTH_SHORT).show();
                                   String fileName = item[which];
                                   if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                                       Log.d(TAG, "Load");
                                       String sdPath = Environment.getExternalStorageDirectory().getAbsolutePath();
                                       String filePath = sdPath + LOCAL_PATH + "/" + fileName;
                                       FileInputStream fis = null;
                                       String content = null;
                                       try {
                                           fis = new FileInputStream(filePath);
                                           ByteArrayOutputStream baos = new ByteArrayOutputStream();
                                           byte[] buffer = new byte[1024];
                                           int len = -1;
                                           while ((len = fis.read(buffer)) != -1) {
                                               baos.write(buffer, 0, len);
                                           }
                                           content = baos.toString();
                                           fis.close();
                                       } catch (FileNotFoundException e) {
                                           e.printStackTrace();
                                       } catch (IOException e) {
                                           e.printStackTrace();
                                       }
                                       String str = "";
                                       try {
                                           JSONArray jsonArray = new JSONArray(content);

                                           for (int i = 0; i < jsonArray.length(); i++) {
                                               JSONArray jsonString = new JSONArray(jsonArray.getString(i));
                                               if (jsonString.length() > 2) {
                                                   int phone = jsonString.getInt(0);
                                                   int game = jsonString.getInt(1);
                                                   if (game >= Transfer_Con.MAX_GP_FIX_GAME_NUM) {
                                                       mGlobalVar.setPackageName(game, jsonString.getString(2));
                                                       mGlobalVar.setUserGameName(game - Transfer_Con.MAX_GP_FIX_GAME_NUM, jsonString.getString(3));
                                                   }
                                                   for (int a = 4; a < jsonString.length(); a++) {
                                                       ptTbl[a - 4] = jsonString.getInt(a);
                                                       str += String.valueOf(ptTbl[a - 4]) + ", ";
                                                   }
                                                   str = "";
                                                   mGlobalVar.saveCoordinateTable(phone, game);

                                                   mGlobalVar.setPtTbl(ptTbl);
                                                   for (int a = 0; a < mGlobalVar.getDeviceMaxButton(); a++) {
                                                       g_u8DataBuf[a * 2] = (byte) (ptTbl[a] & 0xff);
                                                       g_u8DataBuf[a * 2 + 1] = (byte) (ptTbl[a] >> 8);
                                                   }
                                                   if (mGlobalVar.set_CurPtTbl((byte) (mGlobalVar.getDeviceMaxButton() * 2), (byte) 0, g_u8DataBuf)) {

                                                       for (int a = 0; a < mGlobalVar.getDeviceMaxButton(); a++) {
                                                           g_u8DataBuf[a * 2] = (byte) (ptTbl[mGlobalVar.getDeviceMaxButton() + a] & 0xff);
                                                           g_u8DataBuf[a * 2 + 1] = (byte) (ptTbl[mGlobalVar.getDeviceMaxButton() + a] >> 8);
                                                       }
                                                       if (mGlobalVar.set_CurPtTbl((byte) (mGlobalVar.getDeviceMaxButton() * 2), (byte) 1, g_u8DataBuf)) {
                                                           mGlobalVar.tranSet_Value(Transfer_Con.HID_CMD_SAVE_POINT_TBL, mGlobalVar.getmCurPhone(), mGlobalVar.getmCurGame());
                                                       }
                                                   }


                                               }
                                           }
                                       } catch (Exception e) {
                                           e.printStackTrace();
                                       }

                                       Toast.makeText(MainActivity.this, getResources().getString(R.string.string_pop_file_load_success) + content, Toast.LENGTH_SHORT).show();
                                   } else {
                                       Toast.makeText(MainActivity.this, getResources().getString(R.string.string_pop_file_load_fail), Toast.LENGTH_SHORT).show();
                                   }
                               }

                           }).create().show();
                    }
               }
           }
        });
        rl_device_data_attr_save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                final EditText editText = new EditText(MainActivity.this);
                editText.setHint("SOE_AET_TBL");
                editText.setSingleLine();
                builder.setTitle(getResources().getString(R.string.string_pop_data_save_dialog_filename))
                        .setView(editText)
                        .setMessage(getResources().getString(R.string.string_pop_data_save_dialog_input_filename))
                        .setPositiveButton(getResources().getString(R.string.string_pop_confirm), new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                                String strFileName = "SOE_AET_TBL";

                                if(!android.text.TextUtils.isEmpty(editText.getText()))
                                    strFileName = editText.getText().toString();

                                boolean bHasData = false;
                                byte [] u8tAutoEventTable = new byte[Transfer_Con.MAX_AUTOEVENT_LENGTH];
                                byte[][] u8tAttrTable = new byte[mGlobalVar.getDeviceMaxButton()][3];
                                final int length = Transfer_Con.HID_PACKET_SIZE - 18;

                                for(int a=0;a<Transfer_Con.MAX_AUTOEVENT_LENGTH;a+=length) {
                                    if(mGlobalVar.tranGet_Value(Transfer_Con.HID_CMD_GET_AEV_TBL, a, (a+length>=Transfer_Con.MAX_AUTOEVENT_LENGTH)?(Transfer_Con.MAX_AUTOEVENT_LENGTH-a):length, g_u8DataBuf))
                                    {
                                        System.arraycopy(g_u8DataBuf,16,u8tAutoEventTable,a,(a+length>=Transfer_Con.MAX_AUTOEVENT_LENGTH)?(Transfer_Con.MAX_AUTOEVENT_LENGTH-a):length);
                                        bHasData = true;
                                    }
                                }
                                for(int a=0;a<3;a++) {
                                    if(mGlobalVar.tranGet_Value(Transfer_Con.HID_CMD_GET_KEY_ATTR, a, 0, g_u8DataBuf))
                                    {
                                        for(int k=0;k<mGlobalVar.getDeviceMaxButton();k++)
                                        {
                                            u8tAttrTable[k][a] = g_u8DataBuf[16+k];
                                        }
                                        bHasData = true;
                                    }
                                }

                                if(bHasData)
                                {
                                    String str="";
                                    JSONArray jsonArray = new JSONArray();
                                    for (byte data : u8tAutoEventTable) {
                                        jsonArray.put(data);
                                        str+=String.valueOf(data&0xff)+",";
                                    }

                                    Log.d(TAG,str);
                                    str="";
                                    for(byte[] data :u8tAttrTable)
                                    {
                                        for(byte data1 : data)
                                        {
                                            jsonArray.put(data1);
                                            str+=String.valueOf(data1&0xff)+",";
                                        }
                                    }
                                    Log.d(TAG,str);
                                    if (Build.VERSION.SDK_INT >= 26 && checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                                            != PackageManager.PERMISSION_GRANTED) {
                                        Toast.makeText(MainActivity.this, getResources().getString(R.string.string_pop_file_save_fail), Toast.LENGTH_SHORT).show();
                                        requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
                                    } else {
                                        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {

                                            String fileName = strFileName+".aet";
                                            String fileContent = jsonArray.toString();
                                            //得到指定文件的输出流
                                            String sdPath = Environment.getExternalStorageDirectory().getAbsolutePath();
                                            File file = new File(sdPath + LOCAL_PATH);
                                            if (!file.exists()) {
                                                if (file.mkdirs())//;//创建文件夹
                                                {
                                                    Log.d(TAG, "创建成功");
                                                } else {
                                                    Log.d(TAG, "创建失败");
                                                }
                                            }
                                            String filePath = sdPath + LOCAL_PATH+"/" + fileName;
                                            String filesPath = getExternalFilesDir(null).getAbsolutePath();
                                            System.out.println(filesPath);
                                            FileOutputStream fos = null;
                                            try {
                                                fos = new FileOutputStream(filePath);
                                                fos.write(fileContent.getBytes("utf-8"));
                                                fos.close();
                                            } catch (FileNotFoundException e) {
                                                e.printStackTrace();
                                            } catch (UnsupportedEncodingException e) {
                                                e.printStackTrace();
                                            } catch (IOException e) {
                                                e.printStackTrace();
                                            }
                                            Toast.makeText(MainActivity.this, getResources().getString(R.string.string_pop_file_save_success) + filePath, Toast.LENGTH_SHORT).show();
                                        } else {
                                            Toast.makeText(MainActivity.this, getResources().getString(R.string.string_pop_file_save_fail), Toast.LENGTH_SHORT).show();
                                        }
                                    }
                                }
                                else
                                {
                                    Toast.makeText(MainActivity.this,getResources().getString(R.string.string_pop_file_save_no_data),Toast.LENGTH_SHORT).show();
                                }
                            }
                        }).create().show();


            }
        });




        rl_device_data_attr_load.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (Build.VERSION.SDK_INT >= 26 && checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        != PackageManager.PERMISSION_GRANTED) {
                    requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
                } else {
                ArrayList<String> fileList = getFileList("aet");
                final String[] item = new String[fileList.size()];
                for(int a=0;a<fileList.size();a++)
                    item[a] = fileList.get(a);

                AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                builder.setTitle(getResources().getString(R.string.string_pop_data_load_select_filename))
                        .setItems(item, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                //Toast.makeText(MainActivity.this,String.valueOf(which),Toast.LENGTH_SHORT).show();
                                String fileName = item[which];
                                byte [] u8tAutoEventTable = new byte[Transfer_Con.MAX_AUTOEVENT_LENGTH];
                                byte[][] u8tAttrTable = new byte[mGlobalVar.getDeviceMaxButton()][3];
                                final int length = Transfer_Con.HID_PACKET_SIZE - 18;

                                    if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {

                                        Log.d(TAG, "Load");

                                        String sdPath = Environment.getExternalStorageDirectory().getAbsolutePath();
                                        String filePath = sdPath + LOCAL_PATH+"/" + fileName;
                                        FileInputStream fis = null;
                                        String content = null;
                                        try {
                                            fis = new FileInputStream(filePath);
                                            ByteArrayOutputStream baos = new ByteArrayOutputStream();
                                            byte[] buffer = new byte[1024];
                                            int len = -1;
                                            while ((len = fis.read(buffer)) != -1) {
                                                baos.write(buffer, 0, len);
                                            }
                                            content = baos.toString();
                                            fis.close();
                                        } catch (FileNotFoundException e) {
                                            e.printStackTrace();
                                        } catch (IOException e) {
                                            e.printStackTrace();
                                        }
                                        //String str = "";
                                        try {
                                            JSONArray jsonArray = new JSONArray(content);
                                            //

                                            if(jsonArray.length()>=Transfer_Con.MAX_AUTOEVENT_LENGTH) {
                                                for (int a = 0; a < Transfer_Con.MAX_AUTOEVENT_LENGTH; a++) {
                                                    u8tAutoEventTable[a] = (byte) jsonArray.getInt(a);
                                                    //str+=String.valueOf(u8tAutoEventTable[a]&0xff)+",";
                                                }

                                                for (int a = 0; a < Transfer_Con.MAX_AUTOEVENT_LENGTH; a += length) {
                                                    System.arraycopy(u8tAutoEventTable, a, g_u8DataBuf, 0, (a + length >= Transfer_Con.MAX_AUTOEVENT_LENGTH) ? (Transfer_Con.MAX_AUTOEVENT_LENGTH - a) : length);

                                                    if (mGlobalVar.tranSet_MultiValue(Transfer_Con.HID_CMD_SET_AEV_TBL, a, (a + length >= Transfer_Con.MAX_AUTOEVENT_LENGTH) ? (Transfer_Con.MAX_AUTOEVENT_LENGTH - a) : length, g_u8DataBuf)) {

                                                    }
                                                    //Thread.sleep(100);
                                                }
                                            }
                                            //Log.d(TAG,str);
                                            //str="";
                                            //Log.d(TAG,String.format("file l=%d,avt l=%d,total l=%d",jsonArray.length(),Transfer_Con.MAX_AUTOEVENT_LENGTH,Transfer_Con.MAX_AUTOEVENT_LENGTH+mGlobalVar.getDeviceMaxButton()*3));
                                            if(jsonArray.length()>=(Transfer_Con.MAX_AUTOEVENT_LENGTH+mGlobalVar.getDeviceMaxButton()*3))
                                            {

                                                for (int a = 0; a < mGlobalVar.getDeviceMaxButton(); a++)
                                                {
                                                    for(int i=0;i<3;i++) {
                                                        u8tAttrTable[a][i] = (byte)jsonArray.getInt(Transfer_Con.MAX_AUTOEVENT_LENGTH+i+3*a);
                                                    }
                                                }
                                                for (int a = 0; a < 3; a++) {
                                                    for (int k = 0; k < mGlobalVar.getDeviceMaxButton(); k++) {
                                                        g_u8DataBuf[k] = u8tAttrTable[k][a];
                                                       // str+=String.valueOf(g_u8DataBuf[k]&0xff)+",";
                                                    }

                                                    if (mGlobalVar.tranSet_MultiValue(Transfer_Con.HID_CMD_SET_KEY_ATTR, a, mGlobalVar.getDeviceMaxButton(), g_u8DataBuf)) {

                                                    }
                                                    //Thread.sleep(20);
                                                }
                                                if (mGlobalVar.tranSet_Value(Transfer_Con.HID_CMD_SAVE_DATA,0,0))
                                                {
                                                    Log.d(TAG, "attr write back ok: ");
                                                }
                                               // Log.d(TAG,str);
                                            }
                                        } catch (Exception e) {
                                            e.printStackTrace();
                                        }

                                        Toast.makeText(MainActivity.this, getResources().getString(R.string.string_pop_file_load_success) + content, Toast.LENGTH_SHORT).show();
                                    } else {
                                        Toast.makeText(MainActivity.this, getResources().getString(R.string.string_pop_file_load_fail), Toast.LENGTH_SHORT).show();
                                    }
                                }
                        })
                        .create().show();
                }
            }
        });
    }

    void showAppSettingAbout()
    {
        View view = LayoutInflater.from(MainActivity.this).inflate(R.layout.app_about_layout,null,false);
        ImageView button = (ImageView)view.findViewById(R.id.iv_app_about_exit);
        RelativeLayout layout_app_about_micromsg = (RelativeLayout)view.findViewById(R.id.layout_app_about_micromsg);
        RelativeLayout layout_app_about_web = (RelativeLayout)view.findViewById(R.id.layout_app_about_web);
        RelativeLayout layout_app_about_qq = (RelativeLayout)view.findViewById(R.id.layout_app_about_QQ);
        RelativeLayout layout_app_about_qq_user = (RelativeLayout)view.findViewById(R.id.layout_app_about_QQ_User);
        TextView layout_tx_web = (TextView)view.findViewById(R.id.tx_web);
        final PopupWindow popupWindow = new PopupWindow(view,ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.MATCH_PARENT,true);
        popupWindow.setTouchable(true);
        Resources resources = getResources();
        Configuration config = resources.getConfiguration();
        DisplayMetrics dm = resources.getDisplayMetrics();
        String language = config.locale.getLanguage();
        final Uri uri;
        if (language.contains("en")) {
            config.locale = Locale.ENGLISH;
            layout_app_about_micromsg.setVisibility(View.GONE);
            layout_app_about_qq.setVisibility(View.GONE);
            layout_app_about_qq_user.setVisibility(View.GONE);
            layout_tx_web.setText("https://www.abazartech.com");
            uri = Uri.parse("https://www.abazartech.com/");
        } else {
            layout_tx_web.setText("http://www.opd-display.com");
            uri = Uri.parse("http://www.opd-display.com");
        }
        popupWindow.setTouchInterceptor(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return false;
            }
        });
        popupWindow.setBackgroundDrawable(new ColorDrawable(0xFFF8F8F8));
        //popupWindow.showAsDropDown(v);  //showAsDropDown(v,50,0);
        popupWindow.showAtLocation(view,Gravity.CENTER|Gravity.BOTTOM,0,0);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });
        layout_app_about_web.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //Uri uri = Uri.parse("http://www.opd-display.com");
                Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                startActivity(intent);
            }
        });
    }
    void showAppSettingProduct()
    {
        View view = LayoutInflater.from(MainActivity.this).inflate(R.layout.app_product_layout,null,false);
        ImageView button = (ImageView)view.findViewById(R.id.iv_app_product_exit);

        final PopupWindow popupWindow = new PopupWindow(view,ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.MATCH_PARENT,true);
        popupWindow.setTouchable(true);
        popupWindow.setTouchInterceptor(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return false;
            }
        });
        popupWindow.setBackgroundDrawable(new ColorDrawable(0xFFF8F8F8));
        //popupWindow.showAsDropDown(v);  //showAsDropDown(v,50,0);
        popupWindow.showAtLocation(view,Gravity.CENTER|Gravity.BOTTOM,0,0);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });
    }

    private void getFiles(ArrayList<File> list, String filePath) {
        File[] allFiles = new File(filePath).listFiles();
        if (allFiles != null) { // 若文件不为空，则遍历文件长度
            for (int i = 0; i < allFiles.length; i++) {
                File file = allFiles[i];
                if (file.isFile()) {
                    list.add(file);
                }
            }
        }
    }
    public ArrayList<String> getFileList(String extName) {
        ArrayList<String> fileList = new ArrayList<>();
        ArrayList<File> list = new ArrayList<File>();
        String sdPath = Environment.getExternalStorageDirectory().getAbsolutePath();
        String filePath = sdPath + LOCAL_PATH+"/";
        getFiles(list, filePath);
        for (int i = 0; i < list.size(); i++) {
            String mPicName = list.get(i).getName();
            String substring = mPicName.substring(mPicName.lastIndexOf(".") + 1);
            if(substring.equals(extName))
            {
                fileList.add(mPicName);
                Log.d(TAG,mPicName);
            }
        }
        return fileList;
    }


    public int checkGPVersion()
    {
        byte len = 0;
        int start_addr = 0;

        if(mGlobalVar.getIsCurDeviceKB())
            start_addr = 0x0ee1;
        else
            start_addr = 0x1ee1;
        //if(g_lCodeLen==0)
        g_lCodeLen = LoadCode("");
       // String str2 ="wwww: ";
        for (int a = 0; a < 13; a++) {
            //str2 += String.valueOf(g_u8CodeBuf[start_addr + a]&0xff)+", ";
            if (g_u8CodeBuf[start_addr + a] == 0) {
                len = (byte) a;
                break;
            }
        }
        //Log.d(TAG,str2);
        byte[] temp = new byte[len];
        int codeVersion = 0;
        System.arraycopy(g_u8CodeBuf, start_addr, temp, 0, len);
        String str = new String(temp);
        String[] str1 = str.split("\\.");
        codeVersion = Integer.parseInt(str1[0]);
        codeVersion = (codeVersion << 16) + Integer.parseInt(str1[1]);
        codeVersion = (codeVersion << 8) + Integer.parseInt(str1[2]);

        return (codeVersion);
    }


    boolean b_isNeedToUpdate =false;
    PopupWindow popupWindowDeviceUpdate;
    boolean bIspopupWindowDeviceUpdateShow = false;
    void showDeviceUpdate()
    {
        long sModel=0;
        //View view = LayoutInflater.from(MainActivity.this).inflate(R.layout.device_update_layout,null,false);
        ImageView button = (ImageView)device_update_layout.findViewById(R.id.iv_device_update_back);
        Button btn_device_update_version_check = (Button)device_update_layout.findViewById(R.id.btn_device_update_version_check);

        TextView tv_device_update_device_name = (TextView)device_update_layout.findViewById(R.id.tv_device_update_device_name);
        RelativeLayout rl = (RelativeLayout)device_update_layout.findViewById(R.id.rl_device_update_introduce);

        if(mGlobalVar.getIsCurDeviceKB())
        {
            rl.setVisibility(View.GONE);
        }
        tv_device_update_version_cur.setText(mGlobalVar.getStrFwVer());

        if(mGlobalVar.getbIsUsbConnect()) {
            if(!mGlobalVar.getbIsTransferMode()) {
                CMD_Connect(USBCMD_TIMEOUT);
                SyncPackno();
                sModel= GetDeviceModel();
                long sDID = GetDeviceID();
                if((sModel==(long)Transfer_Con.HID_BOOT_MODEL_NAME_GM1)||(sModel==(long)Transfer_Con.HID_BOOT_MODEL_NAME_GN1))
                {
                    mGlobalVar.setDeviceName("GM1");
                }
                else if((sModel==(long)Transfer_Con.HID_BOOT_MODEL_NAME_GM2)||(sModel==(long)Transfer_Con.HID_BOOT_MODEL_NAME_GN2))
                {
                    mGlobalVar.setDeviceName("GM2");
                }
                else if(sModel==(long)Transfer_Con.HID_BOOT_MODEL_NAME_HN2)
                {
                    mGlobalVar.setDeviceName("HN2");
                }
                else if(sModel==(long)Transfer_Con.HID_BOOT_MODEL_NAME_MP1)
                {
                    mGlobalVar.setDeviceName("MP1");
                }
                else if(sModel==(long)Transfer_Con.HID_BOOT_MODEL_NAME_BX1)
                {
                    mGlobalVar.setDeviceName("BX1");
                }
                else if(sModel==(long)Transfer_Con.HID_BOOT_MODEL_NAME_BX2)
                {
                    mGlobalVar.setDeviceName("BX2");
                }
                else if(sModel==(long)Transfer_Con.HID_BOOT_MODEL_NAME_MR1)
                {
                    mGlobalVar.setDeviceName("MR1");
                }
                else if(sModel==(long)Transfer_Con.HID_BOOT_MODEL_NAME_U41)
                {
                    mGlobalVar.setDeviceName("U41");
                }
                else
                {
                    if(sDID==0x00C05204)
                    {
                        mGlobalVar.setDeviceName("HN1");
                    }
                    else {
                        mGlobalVar.setDeviceName("NA");
                    }
                }
                if(mGlobalVar.getDeviceIndex()!=mGlobalVar.getLastConnectDeviceIndex())
                {
                    mGlobalVar.setLastConnectDeviceIndex(mGlobalVar.getDeviceIndex());
                    saveUserData(false);
                }
            }
            tv_device_update_device_name.setText(mGlobalVar.getDeviceName());
        }
        else if(bluetoothUtils.getBleConnectStatus())
        {
            tv_device_update_device_name.setText(bluetoothUtils.getBleDeviceName());
            tv_device_update_version_cur.setText(bluetoothUtils.getBleStrFwVer());
        }
        else
            tv_device_update_device_name.setText(getResources().getString(R.string.string_device_update_device_name));
        popupWindowDeviceUpdate = new PopupWindow(device_update_layout,ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.MATCH_PARENT,true);
        popupWindowDeviceUpdate.setTouchable(true);

        final ImageView imageView = new ImageView(MainActivity.this);
        if((sModel==(long)Transfer_Con.HID_BOOT_MODEL_NAME_GM1)||(sModel==(long)Transfer_Con.HID_BOOT_MODEL_NAME_GN1))
            imageView.setImageDrawable(getResources().getDrawable(R.drawable.update_step4_m1));
        else
            imageView.setImageDrawable(getResources().getDrawable(R.drawable.update_step4));

        //imageView

        popupWindowDeviceUpdate.setTouchInterceptor(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return false;
            }
        });
        popupWindowDeviceUpdate.setBackgroundDrawable(new ColorDrawable(0xFFF8F8F8));
        //popupWindow.showAsDropDown(v);  //showAsDropDown(v,50,0);
        popupWindowDeviceUpdate.showAtLocation(device_update_layout,Gravity.CENTER|Gravity.BOTTOM,0,0);
        bIspopupWindowDeviceUpdateShow = true;
        popupWindowDeviceUpdate.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                bIspopupWindowDeviceUpdateShow = false;
            }
        });

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindowDeviceUpdate.dismiss();
            }
        });

        rl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                bIsAlreadyReadIntroduce = true;
                saveUserData(false);
                View view1 = LayoutInflater.from(MainActivity.this).inflate(R.layout.device_update_guide_layout,null,false);
                ImageView button = (ImageView)view1.findViewById(R.id.iv_device_update_guide_back);
                ImageView iv_device_update_guide_step4_1 = (ImageView)view1.findViewById(R.id.iv_device_update_guide_step4_1);
                ImageView iv_device_update_guide_fail_step1 = (ImageView)view1.findViewById(R.id.iv_device_update_guide_fail_step1);

                if(mGlobalVar.getDeviceIndex()==Transfer_Con.DEVICE_GM1_INDEX) {
                    iv_device_update_guide_step4_1.setImageDrawable(getResources().getDrawable(R.drawable.update_step4_m1));
                    iv_device_update_guide_fail_step1.setImageDrawable(getResources().getDrawable(R.drawable.update_step4_m1));
                }
                else {
                    iv_device_update_guide_step4_1.setImageDrawable(getResources().getDrawable(R.drawable.update_step4));
                    iv_device_update_guide_fail_step1.setImageDrawable(getResources().getDrawable(R.drawable.update_step4));
                }


                final PopupWindow popupWindow = new PopupWindow(view1,ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.MATCH_PARENT,true);
                popupWindow.setTouchable(true);

                popupWindow.setTouchInterceptor(new View.OnTouchListener() {
                    @Override
                    public boolean onTouch(View v, MotionEvent event) {
                        return false;
                    }
                });
                popupWindow.setBackgroundDrawable(new ColorDrawable(0xFFF8F8F8));
                //popupWindow.showAsDropDown(v);  //showAsDropDown(v,50,0);
                popupWindow.showAtLocation(view1,Gravity.CENTER|Gravity.BOTTOM,0,0);

                button.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        popupWindow.dismiss();
                    }
                });
            }
        });

        btn_device_update_version_check.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (mGlobalVar.getbIsUsbConnect()) {

                    final AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                    if(bIsAlreadyReadIntroduce||b_isNeedToUpdate)
                    {
                        b_isNeedToUpdate = false;
                        int ver = checkGPVersion();
                        if ((ver > mGlobalVar.get_IntVersion())||(!mGlobalVar.getbIsTransferMode())||bIsCheckSumDiff) {
                            String str = String.format("%d.%03d.%02d", ver >> 24, (ver & 0xFFFFFF) >> 8, ver & 0xff);
                            //Toast.makeText(MainActivity.this, String.format("%d.%03d.%02d", mGlobalVar.get_IntVersion() >> 24, (mGlobalVar.get_IntVersion() & 0xFFFFFF) >> 8, mGlobalVar.get_IntVersion() & 0xff), Toast.LENGTH_SHORT).show();
                            final ImageView imageView = new ImageView(MainActivity.this);
                            if(mGlobalVar.getbIsTransferMode()) {
                                if ((mGlobalVar.getDeviceIndex() == Transfer_Con.DEVICE_GM1_INDEX) || (mGlobalVar.getDeviceIndex() == Transfer_Con.DEVICE_GM2_INDEX))
                                    imageView.setImageDrawable(getResources().getDrawable(R.drawable.update_step4_m1));
                                else
                                    imageView.setImageDrawable(getResources().getDrawable(R.drawable.update_step4));
                            }
                            builder.setTitle(getResources().getString(R.string.string_pop_device_update_title))
                                    .setMessage(getResources().getString(R.string.string_pop_device_update_found_new_ver) + str + getResources().getString(R.string.string_pop_device_update_found_new_ver_2))
                                    .setPositiveButton(getResources().getString(R.string.string_pop_yes), new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            if (mGlobalVar.getIsCurDeviceKB()) {
                                                if (mGlobalVar.getbIsUsbConnect() && (!mGlobalVar.getbIsTransferMode())) {
                                                    SharedPreferences.Editor editor1 = getSharedPreferences(Transfer_Con.SAVENAME, MODE_PRIVATE).edit();
                                                    editor1.putBoolean("waitUpdate", false);
                                                    editor1.commit();
                                                    UpdateFw();
                                                } else if (mGlobalVar.tranGet_Value((byte) (Transfer_Con.HID_CMD_UPDATE_FW), 0xBB4444BB, 0x44BBBB44, g_u8DataBuf)) {
                                                    if ((g_u8DataBuf[4] == 0x00) && (g_u8DataBuf[5] == 0x30) && (g_u8DataBuf[6] == 0x44) && (g_u8DataBuf[7] == 0x50)) {
                                                        if (g_u8DataBuf[0] == 1) {
                                                            if (mGlobalVar.tranSet_Value((byte) (Transfer_Con.HID_CMD_FW_RESET), 0x55AAAA55, 0xAA5555AA)) {
                                                                handler.postDelayed(runnableUpdate, 500);
                                                            } else {
                                                                AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                                                                builder.setTitle(getResources().getString(R.string.string_pop_device_update_fail)).create().show();
                                                                return;
                                                            }
                                                        } else {
                                                            AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                                                            builder.setTitle(getResources().getString(R.string.string_pop_device_update_fail))
                                                                    .setMessage(getResources().getString(R.string.string_pop_device_update_press_button)).create().show();
                                                            return;
                                                        }
                                                    }
                                                }
                                            }
                                            else
                                            {
                                                final AlertDialog.Builder builderA = new AlertDialog.Builder(MainActivity.this);
                                                mGlobalVar.tranSet_Value((byte) (Transfer_Con.HID_CMD_MP_TEST_PRODUCT_START), 0x00AA0055, 0);
                                                builderA.setMessage(getResources().getString(R.string.string_pop_device_update_found_new_ver_content))
                                                        .setView(imageView)
                                                        .setPositiveButton(getResources().getString(R.string.string_pop_confirm), new DialogInterface.OnClickListener() {
                                                            @Override
                                                            public void onClick(DialogInterface dialog, int which) {
                                                                mGlobalVar.tranSet_Value((byte) (Transfer_Con.HID_CMD_MP_TEST_PRODUCT_END), 0x00AA0055, 0);
                                                                if (mGlobalVar.getbIsUsbConnect() && (!mGlobalVar.getbIsTransferMode())) {
                                                                    SharedPreferences.Editor editor1 = getSharedPreferences(Transfer_Con.SAVENAME, MODE_PRIVATE).edit();
                                                                    editor1.putBoolean("waitUpdate", false);
                                                                    editor1.commit();
                                                                    UpdateFw();
                                                                } else if (mGlobalVar.tranGet_Value((byte) (Transfer_Con.HID_CMD_UPDATE_FW), 0xBB4444BB, 0x44BBBB44, g_u8DataBuf)) {
                                                                    if ((g_u8DataBuf[4] == 0x00) && (g_u8DataBuf[5] == 0x30) && (g_u8DataBuf[6] == 0x44) && (g_u8DataBuf[7] == 0x50)) {
                                                                        if (g_u8DataBuf[0] == 1) {
                                                                            if (mGlobalVar.tranSet_Value((byte) (Transfer_Con.HID_CMD_FW_RESET), 0x55AAAA55, 0xAA5555AA)) {
                                                                                handler.postDelayed(runnableUpdate, 500);
                                                                            } else {
                                                                                AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                                                                                builder.setTitle(getResources().getString(R.string.string_pop_device_update_fail)).create().show();
                                                                                return;
                                                                            }
                                                                        } else {
                                                                            AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                                                                            builder.setTitle(getResources().getString(R.string.string_pop_device_update_fail))
                                                                                    .setMessage(getResources().getString(R.string.string_pop_device_update_press_button)).create().show();
                                                                            return;
                                                                        }
                                                                    }
                                                                }
                                                            }
                                                        })

                                                        .setNegativeButton(getResources().getString(R.string.string_pop_no), new DialogInterface.OnClickListener() {
                                                            @Override
                                                            public void onClick(DialogInterface dialog, int which) {
                                                                mGlobalVar.tranSet_Value((byte) (Transfer_Con.HID_CMD_MP_TEST_PRODUCT_END), 0x00AA0055, 0);
                                                            }
                                                        }).create();
                                                builderA.setCancelable(false);
                                                builderA.show();
                                            }
                                        }
                                    })
                                    .setNegativeButton(getResources().getString(R.string.string_pop_reminder_new_game_later), new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            mGlobalVar.tranSet_Value((byte)(Transfer_Con.HID_CMD_MP_TEST_PRODUCT_END),0x00AA0055,0);
                                        }
                                    }).create();
                            builder.setCancelable(false);
                            builder.show();
                        } else {
                            final AlertDialog.Builder builder1 = new AlertDialog.Builder(MainActivity.this);
                            builder.setTitle(getResources().getString(R.string.string_pop_device_update_title))
                                    .setMessage(getResources().getString(R.string.string_pop_check_update_newest))
                                    .setPositiveButton(getResources().getString(R.string.string_pop_confirm), new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {

                                        }
                                    }).create().show();
                        }
                    }
                    else {
                        builder.setTitle(getResources().getString(R.string.string_pop_device_update_title))
                                .setMessage(getResources().getString(R.string.string_pop_device_update_introduce))
                                .setPositiveButton(getResources().getString(R.string.string_pop_device_update_introduce_already), new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        bIsAlreadyReadIntroduce = true;
                                        saveUserData(false);
                                        int ver = checkGPVersion();
                                        if (ver > mGlobalVar.get_IntVersion()||(!mGlobalVar.getbIsTransferMode())||bIsCheckSumDiff) {

                                            String str = String.format("%d.%03d.%02d", ver >> 24, (ver & 0xFFFFFF) >> 8, ver & 0xff);
                                            final ImageView imageView = new ImageView(MainActivity.this);
                                            if(mGlobalVar.getbIsTransferMode()) {
                                                if ((mGlobalVar.getDeviceIndex() == Transfer_Con.DEVICE_GM1_INDEX) || (mGlobalVar.getDeviceIndex() == Transfer_Con.DEVICE_GM2_INDEX))
                                                    imageView.setImageDrawable(getResources().getDrawable(R.drawable.update_step4_m1));
                                                else
                                                    imageView.setImageDrawable(getResources().getDrawable(R.drawable.update_step4));
                                            }
                                            //Toast.makeText(MainActivity.this, str, Toast.LENGTH_SHORT).show();
                                            final AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);

                                            builder.setTitle(getResources().getString(R.string.string_pop_device_update_title))
                                                    .setMessage(getResources().getString(R.string.string_pop_device_update_found_new_ver) + str + getResources().getString(R.string.string_pop_device_update_found_new_ver_2))
                                                    .setPositiveButton(getResources().getString(R.string.string_pop_yes), new DialogInterface.OnClickListener() {
                                                        @Override
                                                        public void onClick(DialogInterface dialog, int which) {
                                                            if (mGlobalVar.getIsCurDeviceKB())
                                                            {
                                                                if (mGlobalVar.getbIsUsbConnect() && (!mGlobalVar.getbIsTransferMode())) {
                                                                    SharedPreferences.Editor editor1 = getSharedPreferences(Transfer_Con.SAVENAME, MODE_PRIVATE).edit();
                                                                    editor1.putBoolean("waitUpdate", false);
                                                                    editor1.commit();
                                                                    UpdateFw();
                                                                } else if (mGlobalVar.tranGet_Value((byte) (Transfer_Con.HID_CMD_UPDATE_FW), 0xBB4444BB, 0x44BBBB44, g_u8DataBuf)) {
                                                                    if ((g_u8DataBuf[4] == 0x00) && (g_u8DataBuf[5] == 0x30) && (g_u8DataBuf[6] == 0x44) && (g_u8DataBuf[7] == 0x50)) {
                                                                        if (g_u8DataBuf[0] == 1) {
                                                                            if (mGlobalVar.tranSet_Value((byte) (Transfer_Con.HID_CMD_FW_RESET), 0x55AAAA55, 0xAA5555AA)) {
                                                                                handler.postDelayed(runnableUpdate, 500);
                                                                            } else {
                                                                                AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                                                                                builder.setTitle(getResources().getString(R.string.string_pop_device_update_fail)).create().show();
                                                                                return;
                                                                            }
                                                                        } else {
                                                                            AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                                                                            builder.setTitle(getResources().getString(R.string.string_pop_device_update_fail))
                                                                                    .setMessage(getResources().getString(R.string.string_pop_device_update_press_button)).create().show();
                                                                            return;
                                                                        }
                                                                    }
                                                                }
                                                            }
                                                            else {
                                                                mGlobalVar.tranSet_Value((byte) (Transfer_Con.HID_CMD_MP_TEST_PRODUCT_START), 0x00AA0055, 0);
                                                                builder.setMessage(getResources().getString(R.string.string_pop_device_update_found_new_ver_content))
                                                                        .setView(imageView)
                                                                        .setPositiveButton(getResources().getString(R.string.string_pop_confirm), new DialogInterface.OnClickListener() {
                                                                            @Override
                                                                            public void onClick(DialogInterface dialog, int which) {
                                                                                mGlobalVar.tranSet_Value((byte) (Transfer_Con.HID_CMD_MP_TEST_PRODUCT_END), 0x00AA0055, 0);
                                                                                if (mGlobalVar.getbIsUsbConnect() && (!mGlobalVar.getbIsTransferMode())) {
                                                                                    SharedPreferences.Editor editor1 = getSharedPreferences(Transfer_Con.SAVENAME, MODE_PRIVATE).edit();
                                                                                    editor1.putBoolean("waitUpdate", false);
                                                                                    editor1.commit();
                                                                                    UpdateFw();
                                                                                } else if (mGlobalVar.tranGet_Value((byte) (Transfer_Con.HID_CMD_UPDATE_FW), 0xBB4444BB, 0x44BBBB44, g_u8DataBuf)) {
                                                                                    if ((g_u8DataBuf[4] == 0x00) && (g_u8DataBuf[5] == 0x30) && (g_u8DataBuf[6] == 0x44) && (g_u8DataBuf[7] == 0x50)) {
                                                                                        if (g_u8DataBuf[0] == 1) {
                                                                                            if (mGlobalVar.tranSet_Value((byte) (Transfer_Con.HID_CMD_FW_RESET), 0x55AAAA55, 0xAA5555AA)) {
                                                                                                handler.postDelayed(runnableUpdate, 1500);
                                                                                            } else {
                                                                                                AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                                                                                                builder.setTitle(getResources().getString(R.string.string_pop_device_update_fail)).create().show();
                                                                                                return;
                                                                                            }
                                                                                        } else {
                                                                                            AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                                                                                            builder.setTitle(getResources().getString(R.string.string_pop_device_update_fail))
                                                                                                    .setMessage(getResources().getString(R.string.string_pop_device_update_press_button)).create().show();
                                                                                            return;
                                                                                        }
                                                                                    }
                                                                                }
                                                                            }
                                                                        })
                                                                        .setNegativeButton(getResources().getString(R.string.string_pop_no), new DialogInterface.OnClickListener() {
                                                                            @Override
                                                                            public void onClick(DialogInterface dialog, int which) {
                                                                                mGlobalVar.tranSet_Value((byte) (Transfer_Con.HID_CMD_MP_TEST_PRODUCT_END), 0x00AA0055, 0);
                                                                            }
                                                                        }).create();
                                                                builder.setCancelable(false);
                                                                builder.show();
                                                            }
                                                        }
                                                    })
                                                    .setNegativeButton(getResources().getString(R.string.string_pop_reminder_new_game_later), new DialogInterface.OnClickListener() {
                                                        @Override
                                                        public void onClick(DialogInterface dialog, int which) {
                                                            mGlobalVar.tranSet_Value((byte)(Transfer_Con.HID_CMD_MP_TEST_PRODUCT_END),0x00AA0055,0);
                                                        }
                                                    }).create();
                                                    builder.setCancelable(false);
                                                    builder.show();
                                        } else {
                                            final AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                                            builder.setTitle(getResources().getString(R.string.string_pop_device_update_title))
                                                    .setMessage(getResources().getString(R.string.string_pop_check_update_newest))
                                                    .setPositiveButton(getResources().getString(R.string.string_pop_confirm), new DialogInterface.OnClickListener() {
                                                        @Override
                                                        public void onClick(DialogInterface dialog, int which) {

                                                        }
                                                    }).create().show();
                                        }
                                    }
                                })
                                .setNegativeButton(getResources().getString(R.string.string_pop_device_update_introduce_not_yet), new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {

                                    }
                                }).create().show();
                    }

                }
                else if(bluetoothUtils.getBleConnectStatus())
                {
                    if(true)//bluetoothUtils.getBleCodeVer()>bluetoothUtils.getBleIntFwVer())
                    {
                        final AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                        String str = String.format("%d.%03d.%02d", bluetoothUtils.getBleCodeVer() >> 24, (bluetoothUtils.getBleCodeVer() & 0xFFFFFF) >> 8, bluetoothUtils.getBleCodeVer() & 0xff);
                        //Toast.makeText(MainActivity.this, String.format("%d.%03d.%02d", mGlobalVar.get_IntVersion() >> 24, (mGlobalVar.get_IntVersion() & 0xFFFFFF) >> 8, mGlobalVar.get_IntVersion() & 0xff), Toast.LENGTH_SHORT).show();
                        builder.setTitle(getResources().getString(R.string.string_pop_device_update_title))
                                .setMessage(getResources().getString(R.string.string_pop_device_update_found_new_ver) + str + getResources().getString(R.string.string_pop_device_update_found_new_ver_2))
                                .setPositiveButton(getResources().getString(R.string.string_pop_yes), new DialogInterface.OnClickListener() {

                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {

                                        pDialog = new ProgressDialog(MainActivity.this);
                                        m_progress = 0;
                                        pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                                        pDialog.setTitle(getResources().getString(R.string.string_pop_device_update_title));
                                        pDialog.setMessage(getResources().getString(R.string.string_pop_update_program));
                                        //pDialog.setIcon(R.drawable.ic_launcher);
                                        pDialog.setProgress(0);
                                        pDialog.setIndeterminate(false);
                                        pDialog.setCancelable(true);
                                        pDialog.show();

                                        bluetoothUtils.OTAUpdateFw(new BluetoothUtils.OnUpdateListener() {
                                            @Override
                                            public void onUpdateError(int e) {
                                                pDialog.setMessage("升级失败！");
                                            }

                                            @Override
                                            public void onUpdating(int progress, long total) {
                                                pDialog.setProgress((int)(progress*100/total));

                                            }

                                            @Override
                                            public void onUpdateStage(int stage) {
                                                switch (stage)
                                                {
                                                    case BluetoothUtils.OTA_STAGE.OTA_STA_LOAD_FILE:
                                                        pDialog.setMessage("读取文件");
                                                        break;
                                                    case BluetoothUtils.OTA_STAGE.OTA_STA_GET_INFO:
                                                        pDialog.setMessage("获取设备信息");
                                                        break;
                                                    case BluetoothUtils.OTA_STAGE.OTA_STA_ERASE:
                                                        pDialog.setMessage("正在擦除...");
                                                        break;
                                                    case BluetoothUtils.OTA_STAGE.OTA_STA_PROGRAM:
                                                        pDialog.setMessage("正在写入...");
                                                        break;
                                                    case BluetoothUtils.OTA_STAGE.OTA_STA_VERIFY:
                                                        pDialog.setMessage("正在校验...");
                                                        break;
                                                    case BluetoothUtils.OTA_STAGE.OTA_STA_COMPLETE:
                                                        pDialog.setMessage("升级完成！");
                                                        break;
                                                }
                                            }
                                        });
                                    }
                                })
                                .setNegativeButton(getResources().getString(R.string.string_pop_no), new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {

                                    }
                                }).create().show();
                    }
                    else
                    {
                        final AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                        builder.setTitle(getResources().getString(R.string.string_pop_device_update_title))
                                .setMessage(getResources().getString(R.string.string_pop_check_update_newest))
                                .setPositiveButton(getResources().getString(R.string.string_pop_confirm), new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {

                                    }
                                }).create().show();
                    }
                }
                else
                {
                    final AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                    builder.setTitle(getResources().getString(R.string.string_pop_device_update_title))
                            .setMessage(getResources().getString(R.string.string_pop_device_update_fail_not_connect))
                            .setPositiveButton(getResources().getString(R.string.string_pop_confirm), new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {

                                }
                            }).create().show();
                }
            }
        });
        if(b_isNeedToUpdate) {
            btn_device_update_version_check.performClick();
        }
    }

    void showConnectMode() {

        ImageView button = connect_mode_view.findViewById(R.id.iv_connect_mode_back);
        RelativeLayout rl_connect_mode_gp_mode = connect_mode_view.findViewById(R.id.rl_connect_mode_gp_mode);
        RelativeLayout rl_connect_mode_monitor_mode = connect_mode_view.findViewById(R.id.rl_connect_mode_monitor_mode);
        RelativeLayout rl_connect_mode_gp_connect_mode = connect_mode_view.findViewById(R.id.rl_connect_mode_gp_connect_mode);
        RadioButton rb_connect_mode_mnt_game = connect_mode_view.findViewById(R.id.rb_connect_mode_mnt_game);
        RadioButton rb_connect_mode_mnt_office = connect_mode_view.findViewById(R.id.rb_connect_mode_mnt_office);

        if(mGlobalVar.getbIsUsbConnect()) {
            tv_connect_mode_cnt_sta.setText(mGlobalVar.getDeviceName()+getResources().getString(R.string.string_pop_connect_already_connect));
            iv_connect_mode_cnt_sta.setImageResource(R.drawable.connect);
            rb_connect_mode_normal.setEnabled(true);

            if(mGlobalVar.getIsCurDeviceKB())
            {
                rl_connect_mode_monitor_mode.setVisibility(View.VISIBLE);
                rl_connect_mode_gp_mode.setVisibility(View.GONE);
                rl_connect_mode_gp_connect_mode.setVisibility(View.GONE);
                if(mGlobalVar.tranGet_Value(Transfer_Con.HID_CMD_GET_HW_SETTING,0,0xFF,g_u8DataBuf))
                {
                    if((g_u8DataBuf[0]&0x01)==0x01)
                    {
                        rb_connect_mode_mnt_office.setChecked(true);
                    }
                    else
                    {
                        rb_connect_mode_mnt_game.setChecked(true);
                    }
                }
            }
            else
            {
                rl_connect_mode_gp_mode.setVisibility(View.VISIBLE);
                rl_connect_mode_gp_connect_mode.setVisibility(View.VISIBLE);
                rl_connect_mode_monitor_mode.setVisibility(View.GONE);
            }

            if(mGlobalVar.getDeviceIndex()==Transfer_Con.DEVICE_GM1_INDEX)
            {
                rb_connect_mode_gp_pc.setVisibility(View.VISIBLE);
            }
            else
            {
                rb_connect_mode_gp_pc.setVisibility(View.GONE);
            }
            if(mGlobalVar.tranGet_Value(Transfer_Con.HID_CMD_GET_HW_SETTING,0,0xFF,g_u8DataBuf))
            {
                rb_connect_mode_gp_normal.setEnabled(true);
                rb_connect_mode_gp_touch.setEnabled(true);
                rb_connect_mode_gp_pc.setEnabled(true);
                if((g_u8DataBuf[0]&0x80)==0x80)
                {
                    if((g_u8DataBuf[0]&0x04)==0x04)
                    {
                        rb_connect_mode_gp_pc.setChecked(true);
                        mGlobalVar.setIsPC360Mode(true);
                    }
                    else
                    {
                        rb_connect_mode_gp_normal.setChecked(true);
                        mGlobalVar.setIsPC360Mode(false);
                    }
                    bIsGPNormalMode = true;
                    mGlobalVar.setIsSimulateMode(true);
                }
                else
                {
                    rb_connect_mode_gp_touch.setChecked(true);
                    bIsGPNormalMode = false;
                    mGlobalVar.setIsSimulateMode(false);
                }
            }
        }else if(bluetoothUtils.getBleConnectStatus())
        {
            tv_connect_mode_cnt_sta.setText(bluetoothUtils.getBleDeviceName()+getResources().getString(R.string.string_pop_connect_already_connect));
            iv_connect_mode_cnt_sta.setImageResource(R.drawable.connect);
        }
        else
        {
            tv_connect_mode_cnt_sta.setText(getResources().getString(R.string.string_pop_connect_disconnect));
            iv_connect_mode_cnt_sta.setImageResource(R.drawable.disconnect);
            rb_connect_mode_normal.setEnabled(false);
            rb_connect_mode_gp_normal.setEnabled(false);
            rb_connect_mode_gp_touch.setEnabled(false);
            rb_connect_mode_gp_pc.setEnabled(false);
            mGlobalVar.setIsSimulateMode(false);
            mGlobalVar.setIsPC360Mode(false);
            bIsGPNormalMode = false;
            rl_connect_mode_monitor_mode.setVisibility(View.GONE);
            rl_connect_mode_gp_mode.setVisibility(View.GONE);
            rl_connect_mode_gp_connect_mode.setVisibility(View.GONE);
        }
        if(!mGlobalVar.getIsSimulateMode()) {
            if (mGlobalVar.getIsInjectServerRunning()) {
                rb_connect_mode_inject.setEnabled(true);
                rb_connect_mode_normal.setEnabled(true);
                if (mGlobalVar.getIsInjectData()) {
                    rb_connect_mode_inject.setChecked(true);
                    rb_connect_mode_normal.setEnabled(false);
                    //Toast.makeText(MainActivity.this, "手柄处于兼容模式！", Toast.LENGTH_SHORT).show();
                }
            }
        }

        final PopupWindow popupWindow = new PopupWindow(connect_mode_view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, true);
        popupWindow.setTouchable(true);

        popupWindow.setTouchInterceptor(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return false;
            }
        });
        popupWindow.setBackgroundDrawable(new ColorDrawable(0xFFF8F8F8));
        //popupWindow.showAsDropDown(v);  //showAsDropDown(v,50,0);
        popupWindow.showAtLocation(connect_mode_view, Gravity.CENTER | Gravity.BOTTOM, 0, 0);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });
        iv_connect_mode_cnt_sta.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(!mGlobalVar.getbIsUsbConnect())
                {
                    if(mGlobalVar.myUsbDevice==null) {
                        mGlobalVar.enumDevice();
                    }
                    if(mGlobalVar.myUsbDevice!=null){
                        if(!mGlobalVar.myUsbManager.hasPermission(mGlobalVar.myUsbDevice))
                            requestUSBPermit();
                        else if(mGlobalVar.connectDevice())
                        {
                            if(mGlobalVar.getDeviceIndex()==Transfer_Con.DEVICE_GM1_INDEX)
                            {
                                if (mGlobalVar.tranGet_Value(Transfer_Con.HID_CMD_GET_HW_SETTING, 0, 0x84, g_u8DataBuf)) {
                                    if ((g_u8DataBuf[0] & 0x80) == 0x80) {
                                        if((g_u8DataBuf[0] & 0x04) == 0x04) {
                                            mGlobalVar.setIsPC360Mode(true);
                                            mGlobalVar.setIsSimulateMode(true);
                                        }
                                        else {
                                            mGlobalVar.setIsSimulateMode(true);
                                            mGlobalVar.setIsPC360Mode(false);
                                        }
                                    } else {
                                        mGlobalVar.setIsSimulateMode(false);
                                        mGlobalVar.setIsPC360Mode(false);
                                    }
                                }
                            }
                            else if((mGlobalVar.getDeviceIndex()==Transfer_Con.DEVICE_HN1_INDEX)||(mGlobalVar.getDeviceIndex()==Transfer_Con.DEVICE_HN2_INDEX)){
                                mGlobalVar.setIsPC360Mode(false);
                                if (mGlobalVar.tranGet_Value(Transfer_Con.HID_CMD_GET_HW_SETTING, 0, mGlobalVar.getIsSupportMenuKey() ? 0x80 : 0, g_u8DataBuf)) {
                                    if ((g_u8DataBuf[0] & 0x80) == 0x80) {
                                        mGlobalVar.setIsSimulateMode(true);
                                        bIsGPNormalMode = true;
                                    } else {
                                        mGlobalVar.setIsSimulateMode(false);
                                        bIsGPNormalMode = false;
                                    }
                                }
                            }
                            launchLayout.setVisibility(View.GONE);
                            iv_top_connect.setImageResource(R.drawable.connect);
                            getAllDataAndShow();
                            if(mGlobalVar.getIsCurDeviceGamePad())
                                sendSimulateMode();
                            try {
                                Thread.sleep(100);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                            sendConnectStatus(true,true);
                            //getInjectStatus();
                        }
                    }
                }
                if(!mGlobalVar.getbIsUsbConnect()) {
                    if (bluetoothUtils.connectDevices()) {
                        if (bluetoothUtils.getBleDeviceName().equals("SOE Touch")) {
                            mProgressDialog.create();
                            mProgressDialog.show();
                            Message msg = new Message();
                            msg.what = TO_CNT_BLE_DEVICE;
                            launchHandler.sendMessageDelayed(msg, 1000);//设置在SPLASHTIME时间后，发送消息
                            bluetoothUtils.getDeviceInfo();
                            bluetoothUtils.getDeviceVersion();
                            bluetoothUtils.getDeviceCodeDate();
                            iv_top_connect.setImageResource(R.drawable.connect);
                            iv_connect_mode_cnt_sta.setImageResource(R.drawable.connect);
                            tv_connect_mode_cnt_sta.setText(bluetoothUtils.getBleDeviceName()+getResources().getString(R.string.string_pop_connect_already_connect));
                        }
                    }
                }
            }
        });
        rb_connect_mode_inject.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if(mGlobalVar.getIsInjectMode())
                {
                    return;
                }
                if(mGlobalVar.getbIsUsbConnect())
                {
                    mGlobalVar.setIsInjectMode(true);
                    sendInjectModeSetting(true);
                    try {
                        Thread.sleep(200);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    sendConnectStatus(true,true);
                    saveUserData(false);
                }
                else
                {
                    Toast.makeText(MainActivity.this,getResources().getString(R.string.string_connect_mode_cnt_sta),Toast.LENGTH_SHORT).show();
                }
            }
        });

        rb_connect_mode_normal.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(bIsGPNormalMode) {
                    return;
                }
                if(!mGlobalVar.getIsInjectMode())
                {
                    return;
                }
                if(mGlobalVar.getbIsUsbConnect())
                {
                    mGlobalVar.setIsInjectMode(false);
                    sendInjectModeSetting(false);
                    try {
                        Thread.sleep(200);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    sendConnectStatus(true,true);
                    saveUserData(false);
                }
                else
                {
                    Toast.makeText(MainActivity.this,getResources().getString(R.string.string_connect_mode_cnt_sta),Toast.LENGTH_SHORT).show();
                }
            }
        });

        rb_connect_mode_gp_normal.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if(bIsGPNormalMode&&(!mGlobalVar.getIsPC360Mode())) {
                    return;
                }
                if(mGlobalVar.getbIsUsbConnect())
                {
                    if(mGlobalVar.getDeviceIndex()==Transfer_Con.DEVICE_HN1_INDEX) {
                        if (mGlobalVar.get_IntVersion() < 16777482) {
                            Toast.makeText(MainActivity.this, getResources().getString(R.string.string_pop_connect_mode_version_10), Toast.LENGTH_SHORT).show();
                            rb_connect_mode_gp_touch.setChecked(true);
                            return;
                        }
                    }
                    AlertDialog.Builder builder= new AlertDialog.Builder(MainActivity.this);
                    builder.setTitle(getResources().getString(R.string.string_pop_reminder))
                            .setMessage(getResources().getString(R.string.string_pop_connect_mode_switch_simulator))
                            .setPositiveButton(getResources().getString(R.string.string_pop_connect_mode_switch_yes), new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {

                                    sendConnectStatus1(false);
                                    try {
                                        Thread.sleep(100);
                                    } catch (InterruptedException e) {
                                        e.printStackTrace();
                                    }
                                    mGlobalVar.setIsSimulateMode(true);
                                    mGlobalVar.setIsPC360Mode(false);
                                    if(mGlobalVar.getIsCurDeviceGamePad())
                                        sendSimulateMode();
                                    try {
                                        Thread.sleep(100);
                                    } catch (InterruptedException e) {
                                        e.printStackTrace();
                                    }

                                    if(mGlobalVar.getDeviceIndex()==Transfer_Con.DEVICE_GM1_INDEX)
                                    {
                                        if (mGlobalVar.tranSet_Value(Transfer_Con.HID_CMD_SET_HW_SETTING, (byte) 0x80, 0x84)) {
                                            try {
                                                Thread.sleep(200);
                                            } catch (InterruptedException e) {
                                                e.printStackTrace();
                                            }
                                            mGlobalVar.tranSet_Value(Transfer_Con.HID_CMD_FW_RESET, 0x55AAAA55, 0xAA5555AA);
                                            bIsGPNormalMode = true;

                                        }
                                    }
                                    else if(mGlobalVar.getIsSupportMenuKey()) {
                                        if (mGlobalVar.tranSet_Value(Transfer_Con.HID_CMD_SET_HW_SETTING, (byte) 0x80, 0x80)) {
                                            try {
                                                Thread.sleep(200);
                                            } catch (InterruptedException e) {
                                                e.printStackTrace();
                                            }
                                            mGlobalVar.tranSet_Value(Transfer_Con.HID_CMD_FW_RESET, 0x55AAAA55, 0xAA5555AA);
                                            bIsGPNormalMode = true;

                                        }
                                    }
                                    else
                                    {
                                        if (mGlobalVar.tranSet_Value(Transfer_Con.HID_CMD_SET_HW_SETTING,  0x80, 0x80)) {
                                            try {
                                                Thread.sleep(200);
                                            } catch (InterruptedException e) {
                                                e.printStackTrace();
                                            }
                                            mGlobalVar.tranSet_Value(Transfer_Con.HID_CMD_FW_RESET, 0x55AAAA55, 0xAA5555AA);
                                            bIsGPNormalMode = true;

                                        }
                                    }
                                }
                            })
                            .setNegativeButton(getResources().getString(R.string.string_pop_connect_mode_switch_no), new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    rb_connect_mode_gp_touch.setChecked(true);
                                    bIsGPNormalMode = false;
                                }
                            }).create().show();
                }
                else
                {
                    Toast.makeText(MainActivity.this,getResources().getString(R.string.string_connect_mode_cnt_sta),Toast.LENGTH_SHORT).show();
                }
            }
        });
        rb_connect_mode_gp_touch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if(!bIsGPNormalMode) {
                    return;
                }
                AlertDialog.Builder builder= new AlertDialog.Builder(MainActivity.this);
                builder.setTitle(getResources().getString(R.string.string_pop_reminder))
                        .setMessage(getResources().getString(R.string.string_pop_connect_mode_switch_mobile_game))
                        .setPositiveButton(getResources().getString(R.string.string_pop_connect_mode_switch_yes), new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                mGlobalVar.setIsSimulateMode(false);
                                mGlobalVar.setIsPC360Mode(false);
                                if(mGlobalVar.getIsCurDeviceGamePad())
                                    sendSimulateMode();
                                if(mGlobalVar.getDeviceIndex()==Transfer_Con.DEVICE_GM1_INDEX)
                                {
                                    if (mGlobalVar.tranSet_Value(Transfer_Con.HID_CMD_SET_HW_SETTING, (byte) 0x00, 0x84)) {
                                        try {
                                            Thread.sleep(200);
                                        } catch (InterruptedException e) {
                                            e.printStackTrace();
                                        }
                                        mGlobalVar.tranSet_Value(Transfer_Con.HID_CMD_FW_RESET, 0x55AAAA55, 0xAA5555AA);
                                        bIsGPNormalMode = true;

                                    }
                                }
                                else if(mGlobalVar.getIsSupportMenuKey()) {
                                    if (mGlobalVar.tranSet_Value(Transfer_Con.HID_CMD_SET_HW_SETTING,  0x00, 0x80)) {
                                        try {
                                            Thread.sleep(200);
                                        } catch (InterruptedException e) {
                                            e.printStackTrace();
                                        }
                                        mGlobalVar.tranSet_Value(Transfer_Con.HID_CMD_FW_RESET, 0x55AAAA55, 0xAA5555AA);
                                        bIsGPNormalMode = false;

                                    }
                                }
                                else {
                                    if (mGlobalVar.tranSet_Value(Transfer_Con.HID_CMD_SET_HW_SETTING, (byte) 0x00, 0x80)) {
                                        try {
                                            Thread.sleep(200);
                                        } catch (InterruptedException e) {
                                            e.printStackTrace();
                                        }
                                        mGlobalVar.tranSet_Value(Transfer_Con.HID_CMD_FW_RESET, 0x55AAAA55, 0xAA5555AA);
                                        bIsGPNormalMode = false;
                                    }
                                }
                            }
                        })
                        .setNegativeButton(getResources().getString(R.string.string_pop_connect_mode_switch_no), new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                rb_connect_mode_gp_normal.setChecked(true);
                                bIsGPNormalMode = true;
                            }
                        }).create().show();
            }
        });

        rb_connect_mode_gp_pc.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(mGlobalVar.getbIsUsbConnect())
                {
                    AlertDialog.Builder builder= new AlertDialog.Builder(MainActivity.this);
                    builder.setTitle(getResources().getString(R.string.string_pop_reminder))
                            .setMessage(getResources().getString(R.string.string_pop_connect_mode_switch_pc_mode))
                            .setPositiveButton(getResources().getString(R.string.string_pop_connect_mode_switch_yes), new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {

                                    sendConnectStatus1(false);
                                    try {
                                        Thread.sleep(100);
                                    } catch (InterruptedException e) {
                                        e.printStackTrace();
                                    }
                                    mGlobalVar.setIsSimulateMode(true);
                                    mGlobalVar.setIsPC360Mode(true);
                                    if(mGlobalVar.getIsCurDeviceGamePad())
                                        sendSimulateMode();
                                    try {
                                        Thread.sleep(100);
                                    } catch (InterruptedException e) {
                                        e.printStackTrace();
                                    }
                                    if (mGlobalVar.tranSet_Value(Transfer_Con.HID_CMD_SET_HW_SETTING,  0x84, 0x84)) {
                                        try {
                                            Thread.sleep(200);
                                        } catch (InterruptedException e) {
                                            e.printStackTrace();
                                        }
                                        mGlobalVar.tranSet_Value(Transfer_Con.HID_CMD_FW_RESET, 0x55AAAA55, 0xAA5555AA);
                                        bIsGPNormalMode = true;
                                    }
                                }
                            })
                            .setNegativeButton(getResources().getString(R.string.string_pop_connect_mode_switch_no), new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    if(mGlobalVar.tranGet_Value(Transfer_Con.HID_CMD_GET_HW_SETTING,0,0x84,g_u8DataBuf))
                                    {
                                        if((g_u8DataBuf[0]&0x80)==0x80)
                                        {
                                            if((g_u8DataBuf[0]&0x04)==0x04)
                                            {
                                                rb_connect_mode_gp_pc.setChecked(true);
                                                bIsGPNormalMode = true;
                                                mGlobalVar.setIsSimulateMode(true);
                                                mGlobalVar.setIsPC360Mode(true);
                                            }
                                            else
                                            {
                                                rb_connect_mode_gp_normal.setChecked(true);
                                                bIsGPNormalMode = true;
                                                mGlobalVar.setIsSimulateMode(true);
                                                mGlobalVar.setIsPC360Mode(false);
                                            }
                                        }
                                        else
                                        {
                                            rb_connect_mode_gp_touch.setChecked(true);
                                            bIsGPNormalMode = false;
                                            mGlobalVar.setIsSimulateMode(false);
                                            mGlobalVar.setIsPC360Mode(false);
                                        }
                                    }
                                }
                            }).create().show();
                }
                else
                {
                    Toast.makeText(MainActivity.this,getResources().getString(R.string.string_connect_mode_cnt_sta),Toast.LENGTH_SHORT).show();
                }
            }
        });

        rb_connect_mode_mnt_office.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mGlobalVar.tranSet_Value(Transfer_Con.HID_CMD_SET_HW_SETTING,  0x01, 0x01);
            }
        });
        rb_connect_mode_mnt_game.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mGlobalVar.tranSet_Value(Transfer_Con.HID_CMD_SET_HW_SETTING,  0x00, 0x01);
            }
        });
    }
    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        //USB 拔插动作, 这个方法都会被调用.
        super.onConfigurationChanged(newConfig);
    }
    //
    View inject_verify_view;
    PopupWindow inject_verify_popupWindow;
    TextView tv_inject_verify_time;
    void showInjectVerify() {

        ImageView button = (ImageView) inject_verify_view.findViewById(R.id.iv_inject_verify_back);
        ImageView iv_inject_verify_1 = (ImageView) inject_verify_view.findViewById(R.id.iv_inject_verify_1);
        ImageView iv_inject_verify_2 = (ImageView) inject_verify_view.findViewById(R.id.iv_inject_verify_2);
        ImageView iv_inject_verify_3 = (ImageView) inject_verify_view.findViewById(R.id.iv_inject_verify_3);
        TextView tv_inject_verify_tip = (TextView) inject_verify_view.findViewById(R.id.tv_inject_verify_tip);
        tv_inject_verify_time.setX(mRes_Wid/2);
        tv_inject_verify_time.setY(250);
        iv_inject_verify_1.setX(mRes_Wid/3);
        iv_inject_verify_1.setY(mRes_Hei/3);
        iv_inject_verify_2.setX(mRes_Wid/2);
        iv_inject_verify_2.setY(mRes_Hei/2);
        iv_inject_verify_3.setX(mRes_Wid*2/3);
        iv_inject_verify_3.setY(mRes_Hei*2/3);
        iv_inject_verify_1.setVisibility(View.VISIBLE);
        iv_inject_verify_2.setVisibility(View.VISIBLE);
        iv_inject_verify_3.setVisibility(View.VISIBLE);
        if(bInjectFirstTime)
            tv_inject_verify_tip.setText(getResources().getString(R.string.string_pop_connect_mode_verify1));
        else
            tv_inject_verify_tip.setText(getResources().getString(R.string.string_pop_connect_mode_verify2));
        inject_verify_popupWindow.setTouchable(true);
        mInjectTimeCounter =15;
        mInjectVerifyStep = 0;
        tv_inject_verify_time.setText(String.valueOf(mInjectTimeCounter)+getResources().getString(R.string.string_pop_second));
        inject_verify_popupWindow.setTouchInterceptor(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return false;
            }
        });
        //inject_verify_popupWindow.setBackgroundDrawable(new ColorDrawable(0xFFF8F8F8));
        //popupWindow.showAsDropDown(v);  //showAsDropDown(v,50,0);
        inject_verify_popupWindow.showAtLocation(inject_verify_view, Gravity.CENTER | Gravity.BOTTOM, 0, 0);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                inject_verify_popupWindow.dismiss();
            }
        });
        iv_inject_verify_1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mInjectVerifyStep++;
                v.setVisibility(View.GONE);
            }
        });
        iv_inject_verify_2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mInjectVerifyStep++;
                v.setVisibility(View.GONE);
            }
        });
        iv_inject_verify_3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mInjectVerifyStep++;
                v.setVisibility(View.GONE);
            }
        });
        Message msg = new Message();
        msg.what = INJECT_VERIFY_STATUS;
        launchHandler.sendMessageDelayed(msg, 1000);//设置在SPLASHTIME时间后，发送消息
    }




    void IntToByte(int src,byte[] tar,int start) {
        tar[start] = (byte) (src & 0xFF);
        tar[start+1] = (byte) ((src & 0xFF00) >> 8);
        tar[start+2] = (byte) ((src & 0xFF0000) >> 16);
        tar[start+3] = (byte) ((src & 0xFF000000) >> 24);
    }

    int LoadCode(String sFileName)
    {
        InputStream is = null;
        int filelength = 0,fileout=0;

        if(mGlobalVar.getDeviceIndex()==Transfer_Con.DEVICE_GM1_INDEX)
            is = this.getResources().openRawResource(R.raw.savedata_gm1);
        else if(mGlobalVar.getDeviceIndex()==Transfer_Con.DEVICE_MP1_INDEX)
            is = this.getResources().openRawResource(R.raw.savedata_mp1);
        else if(mGlobalVar.getDeviceIndex()==Transfer_Con.DEVICE_BX1_INDEX)
            is = this.getResources().openRawResource(R.raw.savedata_bx1);
        else if(mGlobalVar.getDeviceIndex()==Transfer_Con.DEVICE_BX2_INDEX)
            is = this.getResources().openRawResource(R.raw.savedata_bx2);
        else if(mGlobalVar.getDeviceIndex()==Transfer_Con.DEVICE_MR1_INDEX)
            is = this.getResources().openRawResource(R.raw.savedata_mr1);
        else if(mGlobalVar.getDeviceIndex()==Transfer_Con.DEVICE_U41_INDEX)
            is = this.getResources().openRawResource(R.raw.savedata_u41);
        else if(mGlobalVar.getDeviceIndex()==Transfer_Con.DEVICE_HN1_INDEX)
            is = this.getResources().openRawResource(R.raw.savedata_hn1);
        else if(mGlobalVar.getDeviceIndex()==Transfer_Con.DEVICE_HN2_INDEX)
            is = this.getResources().openRawResource(R.raw.savedata_hn2);
        else
            return 0;

        try {
            filelength = is.available();
            g_u8CodeBuf =  new byte[filelength];
            int count;
            while((count = is.read(g_u8CodeBuf))>0)
            {
                fileout += count;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        Log.d(TAG, "LoadCode: get="+String.valueOf(filelength)+" Read:" +String.valueOf(fileout));
        if(filelength==fileout)
        {
            return fileout;
        }
        else {

            return 0;
        }
    }

    void SyncPackno()
    {
        //m_uCmdIndex = 1;
        mGlobalVar.setIspuCmdIndex(1);
        byte[] byteCmd = new byte[4];
        IntToByte(1,byteCmd,0);
        mGlobalVar.WriteData(
                ISPCmd_Con.CMD_SYNC_PACKNO,
                byteCmd,
                4,
                USBCMD_TIMEOUT);
        mGlobalVar.ReadData(g_u8DataBuf, 0, USBCMD_TIMEOUT, false);
    }

    byte GetVersion()
    {
        mGlobalVar.WriteData(
                ISPCmd_Con.CMD_GET_VERSION,
                null,
                0,
                USBCMD_TIMEOUT);
        byte[] ucVersion = new byte[1];
        mGlobalVar.ReadData(ucVersion, 1, USBCMD_TIMEOUT, true);
        return ucVersion[0];
    }

    boolean CMD_Connect(int dwMilliseconds)
    {
        boolean ret = false;

        if (mGlobalVar.WriteData(ISPCmd_Con.CMD_CONNECT, null, 0, USBCMD_TIMEOUT_LONG)) {
            ret = mGlobalVar.ReadData(g_u8DataBuf, 0, dwMilliseconds, false);
        }
        return ret;
    }

    long GetDeviceID()
    {
        mGlobalVar.WriteData(
                ISPCmd_Con.CMD_GET_DEVICEID,
                null,
                0,
                USBCMD_TIMEOUT);
        long uID=0;
        byte[] buf = new byte[4];
        mGlobalVar.ReadData(buf, 4, USBCMD_TIMEOUT, true);
        for(int a=0;a<4;a++)
        {
            uID +=  (int)(buf[a]&0x00FF)<<(8*a);
        }
        //uID = buf[0] + (int)(buf[1]&0x00FF)<<8 + (int)(buf[2]&0x00FF)<<16 + (int)(buf[3]&0x00ff)<<24;
        //Log.d(TAG, "GetDeviceID: "+String.valueOf(buf[0])+", "+String.valueOf(buf[1])+", "+String.valueOf(buf[2])+", "+String.valueOf(buf[3])+", "+String.valueOf(uID));
        return uID;
    }
    long GetDeviceModel()
    {
        mGlobalVar.WriteData(
                ISPCmd_Con.CMD_GET_DEVICEMODEL,
                null,
                0,
                USBCMD_TIMEOUT);
        long uID=0;
        byte[] buf = new byte[4];
        mGlobalVar.ReadData(buf, 4, USBCMD_TIMEOUT, true);
        for(int a=0;a<4;a++)
        {
            uID +=  (int)(buf[a]&0x00FF)<<(8*a);
        }
        //uID = buf[0] + (int)(buf[1]&0x00FF)<<8 + (int)(buf[2]&0x00FF)<<16 + (int)(buf[3]&0x00ff)<<24;
        Log.d(TAG, "GetDeviceModel: "+String.valueOf(buf[0])+", "+String.valueOf(buf[1])+", "+String.valueOf(buf[2])+", "+String.valueOf(buf[3])+", "+String.valueOf(uID));
        return uID;
    }

    long GetOPDVersion()
    {
        mGlobalVar.WriteData(
                ISPCmd_Con.CMD_GET_OPD_VER,
                null,
                0,
                USBCMD_TIMEOUT);
        long ulVersion=0;
        byte[] buf = new byte[4];
        mGlobalVar.ReadData(buf, 4, USBCMD_TIMEOUT, true);
        for(int a=0;a<4;a++)
        {
            ulVersion +=  (int)(buf[a]&0x00FF)<<(8*a);
        }
        return ulVersion;
    }

    long GetCheckSum()
    {
        mGlobalVar.WriteData(
                ISPCmd_Con.CMD_GET_CHECKSUM,
                null,
                0,
                USBCMD_TIMEOUT);
        long ulCks=0;
        byte[] buf = new byte[4];
        mGlobalVar.ReadData(buf, 4, USBCMD_TIMEOUT, true);
        for(int a=0;a<4;a++)
        {
            ulCks +=  (int)(buf[a]&0xFF)<<(8*a);
        }
        return ulCks;
    }

    long GetUpdateComplete()
    {
        mGlobalVar.WriteData(
                ISPCmd_Con.CMD_CLR_UPDATE_FLAG,
                null,
                0,
                USBCMD_TIMEOUT);
        long ulCks=0;
        byte[] buf = new byte[4];
        mGlobalVar.ReadData(buf, 4, USBCMD_TIMEOUT, true);
        for(int a=0;a<4;a++)
        {
            ulCks +=  (int)(buf[a]&0x00FF)<<(8*a);
        }
        return ulCks;
    }


    void ReadConfig(long config[])
    {
        mGlobalVar.WriteData(
                ISPCmd_Con.CMD_READ_CONFIG,
                null,
                0,
                USBCMD_TIMEOUT);
        byte[] buf= new byte[16];
        mGlobalVar.ReadData(buf, 16, USBCMD_TIMEOUT, true);
        config[0] = config[1] = 0;
        for(int a=0;a<4;a++)
        {
            config[0] += (int)(buf[a]&0xff)<<(a*8);
            config[1] += (int)(buf[4+a]&0xff)<<(a*8);
        }
        // Log.d(TAG, "ReadConfig: 0x"+Long.toHexString(config[0])+" 0x"+Long.toHexString(config[1]));
    }

    void UpdateConfig(long config[], long response[])
    {
        byte[] buf = new byte[16];
        for(int a=0;a<4;a++)
        {
            buf[a] = (byte)((config[0]>>(a*8))&0xFF);
            buf[4+a] = (byte)((config[1]>>(a*8))&0xFF);
        }
        mGlobalVar.WriteData(
                ISPCmd_Con.CMD_UPDATE_CONFIG,
                buf,
                16,
                USBCMD_TIMEOUT_LONG);
        mGlobalVar.ReadData(buf, 16, USBCMD_TIMEOUT_LONG, true);
        response[0] = response[1] = 0;
        for(int a=0;a<4;a++)
        {
            //Log.d(TAG,"response: "+Integer.toHexString(buf[a]&0xff));
            response[0] += (long) (buf[a]&0xFF)<<(a*8);
            response[1] += (long) (buf[4+a]&0xFF)<<(a*8);
        }
    }


    void UpdateAPROM(long start_addr,long total_len,long cur_addr,byte[]buffer,long[] update_len)
    {
        int write_len = (int)(total_len - (cur_addr - start_addr));
        byte[] acBuffer = new byte[ISPCmd_Con.MAX_BUFFER_SIZE- 8 ];/* cmd, index */
        if (start_addr == cur_addr) {
            if (write_len > ISPCmd_Con.MAX_BUFFER_SIZE - 8 - 8/*start_addr, total_len*/) {
                write_len = ISPCmd_Con.MAX_BUFFER_SIZE - 8  - 8/*start_addr, total_len*/;
            }
            acBuffer[0] = (byte)(start_addr&0xFF);
            acBuffer[1] = (byte)(start_addr>>8&0xFF);
            acBuffer[2] = (byte)(start_addr>>16&0xFF);
            acBuffer[3] = (byte)(start_addr>>24&0xFF);
            acBuffer[4] = (byte)(total_len&0xFF);
            acBuffer[5] = (byte)(total_len>>8&0xFF);
            acBuffer[6] = (byte)(total_len>>16&0xFF);
            acBuffer[7] = (byte)(total_len>>24&0xFF);
            System.arraycopy(buffer,0,acBuffer,8,(int)write_len);
            //memcpy(&acBuffer[0], &start_addr, 4);
            //memcpy(&acBuffer[4], &total_len, 4);
            //memcpy(&acBuffer[8], buffer, write_len);
            mGlobalVar.WriteData(
                    ISPCmd_Con.CMD_UPDATE_APROM,
                    acBuffer,
                    write_len + 8/*start_addr, total_len*/,
                    USBCMD_TIMEOUT_LONG);
            /* First block need erase the chip, need long timeout */
            mGlobalVar.ReadData(g_u8DataBuf, 0, USBCMD_TIMEOUT_LONG, true);
        } else {
            if (write_len > ISPCmd_Con.MAX_BUFFER_SIZE -8 ) {
                write_len = ISPCmd_Con.MAX_BUFFER_SIZE -8;
            }
            System.arraycopy(buffer,0,acBuffer,0,(int)write_len);
            mGlobalVar.WriteData(
                    0,
                    buffer,
                    write_len,
                    USBCMD_TIMEOUT_LONG);
            for(int d=0;d<10000000;)
                d++;
            mGlobalVar.ReadData(g_u8DataBuf, 0, USBCMD_TIMEOUT_LONG, true);
        }

        if (update_len != null) {
            update_len[0] = write_len;
        }
    }

    void UpdateNVM(long start_addr,long total_len,long cur_addr,byte[]buffer,long[] update_len)
    {
        int write_len = (int)(total_len - (cur_addr - start_addr));
        byte[] acBuffer = new byte[ISPCmd_Con.MAX_BUFFER_SIZE- 8 ];/* cmd, index */

        if (start_addr == cur_addr) {
            if (write_len > ISPCmd_Con.MAX_BUFFER_SIZE - 8 - 8/*start_addr, total_len*/) {
                write_len = ISPCmd_Con.MAX_BUFFER_SIZE - 8  - 8/*start_addr, total_len*/;
            }
            acBuffer[0] = (byte)(start_addr&0xFF);
            acBuffer[1] = (byte)(start_addr>>8&0xFF);
            acBuffer[2] = (byte)(start_addr>>16&0xFF);
            acBuffer[3] = (byte)(start_addr>>24&0xFF);
            acBuffer[4] = (byte)(total_len&0xFF);
            acBuffer[5] = (byte)(total_len>>8&0xFF);
            acBuffer[6] = (byte)(total_len>>16&0xFF);
            acBuffer[7] = (byte)(total_len>>24&0xFF);
            System.arraycopy(acBuffer,8,buffer,0,(int)write_len);
            //memcpy(&acBuffer[0], &start_addr, 4);
            //memcpy(&acBuffer[4], &total_len, 4);
            //memcpy(&acBuffer[8], buffer, write_len);
            mGlobalVar.WriteData(
                    ISPCmd_Con.CMD_UPDATE_DATAFLASH,
                    acBuffer,
                    write_len + 8/*start_addr, total_len*/,
                    USBCMD_TIMEOUT_LONG);
            /* First block need erase the chip, need long timeout */
            mGlobalVar.ReadData(g_u8DataBuf, 0, USBCMD_TIMEOUT_LONG, true);
        } else {
            if (write_len > ISPCmd_Con.MAX_BUFFER_SIZE-8) {
                write_len = ISPCmd_Con.MAX_BUFFER_SIZE-8 ;
            }

            mGlobalVar.WriteData(
                    0,
                    buffer,
                    write_len,
                    USBCMD_TIMEOUT_LONG);
            mGlobalVar.ReadData(g_u8DataBuf, 0, USBCMD_TIMEOUT_LONG, true);
        }

        if (update_len != null) {
            update_len[0] = write_len;
        }
    }

    boolean EraseAll()
    {
        boolean ret = false;

        if (mGlobalVar.WriteData(ISPCmd_Con.CMD_ERASE_ALL, null,	0, USBCMD_TIMEOUT_LONG)) {
            for(int a=0;a<10000000;)
                a++;
            ret = mGlobalVar.ReadData(g_u8DataBuf, 0, USBCMD_TIMEOUT_LONG, true);
        }
        return ret;
    }

    boolean CMD_Resend()
    {
        boolean ret = false;

        if (mGlobalVar.WriteData(ISPCmd_Con.CMD_RESEND_PACKET, null, 0, USBCMD_TIMEOUT_LONG)) {
            ret = mGlobalVar.ReadData(g_u8DataBuf, 0, USBCMD_TIMEOUT_LONG, false);
        }

        return ret;
    }

    boolean UpdateSizeInfo(int uID, long uConfig0, long uConfig1)
    {
        int uAPROM_Addr=0;
        int uLDROM_Addr=0;
        int []auSPROM_Addr;
        int uKPROM_Addr=0;
        int uLDROM_Size=0;
        int []auSPROM_Size;
        int uKPROM_Size=0;

        auSPROM_Addr = new int[]{0,0,0};
        auSPROM_Size = new int[]{0,0,0};
        Log.d(TAG, "UpdateSizeInfo: " + Integer.toHexString(uID));
        if (GetInfo(uID, uConfig0, uConfig1, uLDROM_Addr, uAPROM_Addr,auSPROM_Addr, uKPROM_Addr, uLDROM_Size,auSPROM_Size, uKPROM_Size)) {
            Log.d(TAG, "UpdateSizeInfo: puAPROM_Size=0x" + Integer.toHexString(m_uAPROM_Size));
            return true;
        }
        Log.d(TAG, "UpdateSizeInfo: fail rom size=0x" + Integer.toHexString(m_uAPROM_Size));
        return false;
    }

    FLASH_PID_INFO_BASE_T GetInfoDetail(int uPID)
    {
        FLASH_PID_INFO_BASE_T pInfo=new FLASH_PID_INFO_BASE_T();
        int[][] infodata=new int[][]{
                { 128 * 1024,   0 * 1024,  20 * 1024,    0x00020000,   4 * 1024,    0x00C05205}, //NUC126LE4AE
                { 256 * 1024,   0 * 1024,  20 * 1024,    0x00040000,   4 * 1024,    0x00C05204}, //NUC126LG4AE
                { 128 * 1024,   0 * 1024,  20 * 1024,    0x00020000,   4 * 1024,    0x00C05213}, //NUC126SE4AE
                { 256 * 1024,   0 * 1024,  20 * 1024,    0x00040000,   4 * 1024,    0x00C05212}, //NUC126SG4AE
                { 256 * 1024,   0 * 1024,  20 * 1024,    0x00020000,   4 * 1024,    0x00C05231}, //NUC126VG4AE
                { 256 * 1024,   0 * 1024,  20 * 1024,    0x00040000,   4 * 1024,    0x00C05230}, //NUC126KG4AE
        };
        /*
        FLASH_PID_INFO_BASE_T[] g_FlashPIDs = new FLASH_PID_INFO_BASE_T[]{
        //16/07/25
                (FLASH_PID_INFO_BASE_T){ 128 * 1024,   0 * 1024,  20 * 1024,    0x00020000,   4 * 1024,    0x00C05205}, //NUC126LE4AE
        { 256 * 1024,   0 * 1024,  20 * 1024,    0x00040000,   4 * 1024,    0x00C05204}, //NUC126LG4AE
        { 128 * 1024,   0 * 1024,  20 * 1024,    0x00020000,   4 * 1024,    0x00C05213}, //NUC126SE4AE
        { 256 * 1024,   0 * 1024,  20 * 1024,    0x00040000,   4 * 1024,    0x00C05212}, //NUC126SG4AE
        { 256 * 1024,   0 * 1024,  20 * 1024,    0x00020000,   4 * 1024,    0x00C05231}, //NUC126VG4AE
        { 256 * 1024,   0 * 1024,  20 * 1024,    0x00040000,   4 * 1024,    0x00C05230}, //NUC126KG4AE
        };
        */
        int i;

        for (i = 0; i < 6; ++i) {
            if (infodata[i][5] == uPID) {
                pInfo.uProgramMemorySize =infodata[i][0];
                pInfo.uDataFlashSize =infodata[i][1];
                pInfo.uRAMSize =infodata[i][2];
                pInfo.uDataFlashStartAddress =infodata[i][3];
                pInfo.uISPFlashSize =infodata[i][4];
                pInfo.uPID =infodata[i][5];
                break;
            }
        }

        if (!(i < 6)) {
            return null;
        }

        return pInfo;
    }

    boolean GetInfo(int uPID,long uConfig0,long uConfig1,int puLDROM_Addr,int puAPROM_Addr,
                    int auSPROM_Addr[],int puKPROM_Addr, int puLDROM_Size, int auSPROM_Size[], int puKPROM_Size)
    {
        FLASH_PID_INFO_BASE_T flashInfo;
        //memset(&gsPidInfo, 0, sizeof(FLASH_PID_INFO_BASE_T));
        flashInfo = GetInfoDetail(uPID);
        if (flashInfo == null) {
            return false;
        }
        Log.d(TAG, "GetInfo: id = 0x" + Integer.toHexString(uPID));
        Log.d(TAG, "Nvram Size: id = 0x" + Long.toHexString((uConfig1 & 0x000FF800)));
        Log.d(TAG, "uDataFlashSize: id = 0x" + Long.toHexString(flashInfo.uProgramMemorySize));
        //memcpy(&gsPidInfo, &flashInfo, sizeof(FLASH_PID_INFO_BASE_T));


        if ((uPID & 0xFFFFFF00) == 0x00C56400
                || (uPID & 0xFFFFFF00) == 0x00C05200) { //M0564/NUC126
            puLDROM_Addr = ISPCmd_Con.NUMICRO_M0_FLASH_LDROM_ADDR;
            puLDROM_Size = flashInfo.uISPFlashSize;
            puAPROM_Addr = ISPCmd_Con.NUMICRO_M0_FLASH_APROM_ADDR;
            auSPROM_Addr[0] = ISPCmd_Con.NUMICRO_M0_FLASH_SPROM_ADDR;
            auSPROM_Size[0] = ISPCmd_Con.M0564_FLASH_SPROM_SIZE;
            auSPROM_Addr[1] = 0xFFFFFFFF;
            auSPROM_Size[1] = 0;
            auSPROM_Addr[2] = 0xFFFFFFFF;
            auSPROM_Size[2] = 0;
            Log.d(TAG, "GetInfo1: size = 0x" + Long.toHexString(uConfig1));
            if (flashInfo.uDataFlashSize == 0
                    && (uConfig0 & ISPCmd_Con.NUC1XX_FLASH_CONFIG_DFEN) == 0) {
                m_uNVM_Addr = (int)(uConfig1 & 0x000FF800);
                m_uAPROM_Size = (flashInfo.uProgramMemorySize > m_uNVM_Addr)
                        ? m_uNVM_Addr : flashInfo.uProgramMemorySize;
                m_uNVM_Size = flashInfo.uProgramMemorySize - m_uAPROM_Size;

                Log.d(TAG, "GetInfo: id enter here"+Integer.toHexString(m_uNVM_Addr));
            } else {
                m_uAPROM_Size = flashInfo.uProgramMemorySize;
                m_uNVM_Addr = flashInfo.uDataFlashStartAddress;
                m_uNVM_Size = flashInfo.uDataFlashSize;
            }

            puKPROM_Addr = 0xFFFFFFFF;
            puKPROM_Size = 0;
        }
        else if (0x00550505 == m_ulDeviceID) {
            m_uAPROM_Addr = 0x4000;
            m_uAPROM_Size = 0x200000 - m_uAPROM_Addr;
        }
        Log.d(TAG, "GetInfo: size = 0x" + Integer.toHexString(m_uAPROM_Size));
        return true;
    }

    int retry = 0;
    boolean bIsUpdateComplete = false;
    public void Thread_ProgramFlash() {
        int uAddr, uSize;
        byte[] pBuffer;
        m_eProcSts = ISPCmd_Con.EPS_OK;
        pDialog.setCanceledOnTouchOutside(false);
        try {
            if (m_bErase) {
                Log.d(TAG, "run: EraseAll");
                pDialog.setMessage(getResources().getString(R.string.string_pop_update_erase));
                if (EraseAll()) {
                    m_progress = 50;
                    pDialog.setProgress(m_progress);
                    ReadConfig(m_CONFIG);
                    m_progress = 100;
                    pDialog.setProgress(m_progress);
                } else {
                    m_eProcSts = ISPCmd_Con.EPS_ERR_ERASE;
                    Log.d(TAG, "run: Erase error");
                    return;
                }
            }

            if (0x00550505 == m_ulDeviceID)
            {
                m_uAPROM_Addr = 0x4000;
                m_uAPROM_Size = 0x200000 - m_uAPROM_Addr;
            }
            else {
                if (m_bProgram_Config) {
                    //Log.d(TAG,"m_CONFIG_User: 0x" + Integer.toHexString(((int) m_CONFIG_User[0]) ) + "  0x" + Integer.toHexString((int) m_CONFIG_User[1]));
                    m_CONFIG_User[0] = m_CONFIG_User[0] & 0xFFFFFFFD;
                    UpdateConfig(m_CONFIG_User, m_CONFIG);
                    //Log.d(TAG, "run: UpdateConfig: "+Long.toHexString(m_CONFIG_User[0])+" a "+Long.toHexString(m_CONFIG[1]));
                    if ((m_CONFIG_User[0] != m_CONFIG[0]) || (m_CONFIG_User[1] != m_CONFIG[1])) {
                        m_eProcSts = ISPCmd_Con.EPS_ERR_CONFIG;
                        //Set_ThreadAction( & CISPProc::Thread_CheckDisconnect);
                        //Log.d(TAG, "run: UpdateConfig fail" + Long.toHexString(m_CONFIG_User[0])+"="+Long.toHexString(m_CONFIG[0])+"   " + Long.toHexString(m_CONFIG_User[1])+"="+Long.toHexString(m_CONFIG[1]));
                        return;
                    }

                    UpdateSizeInfo((int) m_ulDeviceID, m_CONFIG[0], m_CONFIG[1]);
                    //Log.d(TAG, "run: size = "+ String.valueOf(m_uAPROM_Size));
                }
            }

            if (m_bProgram_APROM) {
                uAddr = m_uAPROM_Addr;
                uSize = g_lCodeLen;
                pBuffer = new byte[64];
                pDialog.setMessage(getResources().getString(R.string.string_pop_update_program));
                m_progress = 0;
                pDialog.setProgress(m_progress);
                if (m_uAPROM_Size < uSize) {
                    m_eProcSts = ISPCmd_Con.EPS_ERR_SIZE;
                    //Set_ThreadAction( & CISPProc::Thread_CheckDisconnect);
                    Log.d(TAG, "run: size error "+ String.valueOf(m_uAPROM_Size));
                    return;
                }
                Log.d(TAG,"code: "+Long.toHexString(m_uAPROM_Size)+"ram: "+Long.toHexString(m_uNVM_Size));
                //PostMessage( * MainHWND, MSG_USER_EVENT, MSG_UPDATE_WRITE_STATUS, 0);
                SyncPackno();
                m_progress = 1;
                pDialog.setProgress(m_progress);
                // Log.d(TAG, "run: UpdateAPROM len=0x"+Long.toHexString(uSize));
                Log.d(TAG,"code: "+Long.toHexString(m_uAPROM_Size)+"ram: "+Long.toHexString(m_uNVM_Size));
                for ( long i = 0;i<uSize ;){
                    System.arraycopy(g_u8CodeBuf,(int)i,pBuffer,0,(int)((i+64)>uSize?(uSize-i):64));
                    long[] uLen=new long[]{0};
                    UpdateAPROM(uAddr, uSize, uAddr + i,
                            (pBuffer),uLen);

                    if (mGlobalVar.getISPResendFlag()) {
                        retry++;
                        return;
                        /*
                        if (i == 0 || !CMD_Resend()) {
                            if(i+uLen[0]>=uSize)
                            {
                                if(mGlobalVar.getIsCurDeviceKB()) {
                                    if(bootVer>=((1<<24)|(1<<8)|2))
                                    {
                                        long cks =   GetCheckSum();
                                        if((codeCks&0xffff)== (cks&0xffff))
                                        {
                                            GetUpdateComplete();
                                            bIsUpdateComplete = true;
                                            pDialog.setCanceledOnTouchOutside(true);
                                            return;
                                        }
                                        else
                                        {
                                            retry++;
                                            return;
                                        }
                                    }
                                    else
                                        return;
                                }
                            }
                                m_eProcSts = ISPCmd_Con.EPS_ERR_APROM;
                                // Set_ThreadAction( & CISPProc::Thread_CheckDisconnect);
                                Log.d(TAG, "run: UpdateAPROM bResendFlag error!");
                                pDialog.setMessage(getResources().getString(R.string.string_pop_device_update_fail));
                                pDialog.setCanceledOnTouchOutside(true);
                                return;
                        }

                         */
                    }

                    i += uLen[0];

                    m_progress = (int)((i * 100) / uSize);
                    pDialog.setProgress(m_progress);
                    //Log.d(TAG, "run: UpdateAPROM i="+String.valueOf(m_progress));
                    //Log.d(TAG,"update i: "+Long.toHexString(i));
                }
                if(mGlobalVar.getIsCurDeviceKB()) {
                    if(bootVer>=((1<<24)|(1<<8)|2))
                    {
                        long cks =   GetCheckSum();
                        if((codeCks&0xffff)== (cks&0xffff))
                        {
                            GetUpdateComplete();
                            bIsUpdateComplete = true;
                        }
                        else
                        {
                            retry++;
                            return;
                        }
                    }
                }
            }

            if (m_bProgram_NVM) {
                uAddr = m_uNVM_Addr;
                uSize = g_lDataLen;
                pBuffer = g_u8DataBuf;

                if (m_uNVM_Size < uSize) {
                    m_eProcSts = ISPCmd_Con.EPS_ERR_SIZE;
                    //Set_ThreadAction( & CISPProc::Thread_CheckDisconnect);
                    return;
                }
                pDialog.setMessage(getResources().getString(R.string.string_pop_update_data));
                m_progress = 0;
                pDialog.setProgress(m_progress);
                // PostMessage( * MainHWND, MSG_USER_EVENT, MSG_UPDATE_WRITE_STATUS, 0);
                SyncPackno();
                m_progress = 1;
                //pDialog.setProgress(m_progress);
                for (long i = 0;i<uSize ;){
                    long []uLen=new long[]{0};
                    UpdateNVM(uAddr, uSize, uAddr + i,pBuffer,uLen);
                    Log.d(TAG, "run: UpdateNVM");
                    if (mGlobalVar.getISPResendFlag()) {
                        if (i == 0 || !CMD_Resend()) {
                            m_eProcSts = ISPCmd_Con.EPS_ERR_NVM;
                            //Set_ThreadAction( & CISPProc::Thread_CheckDisconnect);
                            return;
                        }
                    }
                    m_progress = (int)((i * 100) / uSize);
                    //pDialog.setProgress(m_progress);
                    i += uLen[0];
                }
            }
            if(mGlobalVar.getIsCurDeviceKB()) {
                pDialog.setMessage(getResources().getString(R.string.string_pop_update_complete_mnt));
                handler.postDelayed(runnable, 3000);
            }
            else
                pDialog.setMessage(getResources().getString(R.string.string_pop_update_complete));
            pDialog.setCanceledOnTouchOutside(true);
        } catch (Exception e) {
            Log.d(TAG, "run: "+e.toString());
            pDialog.setMessage(getResources().getString(R.string.string_pop_device_update_fail)+e.toString());
            pDialog.setCanceledOnTouchOutside(true);
        }
        bIsUpdateComplete = true;
    }

    long bootVer = 0;
    long codeCks = 0;

    public void UpdateFw()
    {
        {
            if(mGlobalVar.getbIsTransferMode())
            {
                AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                builder.setTitle(getResources().getString(R.string.string_pop_device_update_fail))
                        .setMessage(getResources().getString(R.string.string_pop_update_press_button))
                        .create().show();
                return;
            }
            pDialog = new ProgressDialog(MainActivity.this);
            m_progress = 0;
            pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            pDialog.setTitle(getResources().getString(R.string.string_pop_device_update_title));
            pDialog.setMessage(getResources().getString(R.string.string_pop_update_program));
            //pDialog.setIcon(R.drawable.ic_launcher);
            pDialog.setProgress(0);
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
            pDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                @Override
                public void onDismiss(DialogInterface dialog) {
                    m_progress = 100;
                }
            });
            CMD_Connect(USBCMD_TIMEOUT);
            SyncPackno();
            byte cVer = GetVersion();
            long sDID = GetDeviceID();
            Log.d(TAG, "update: sDID=" + String.format("0x%X",sDID));
            long sModel = GetDeviceModel();
            Log.d(TAG, "update: Model=" + String.valueOf(sModel));
            bootVer = GetOPDVersion();
            retry = 0;
            bIsUpdateComplete = false;
            if((sModel==(long)Transfer_Con.HID_BOOT_MODEL_NAME_GM1)||(sModel==(long)Transfer_Con.HID_BOOT_MODEL_NAME_GN1))
            {
                mGlobalVar.setDeviceName("GM1");
            }
            else if((sModel==(long)Transfer_Con.HID_BOOT_MODEL_NAME_GM2)||(sModel==(long)Transfer_Con.HID_BOOT_MODEL_NAME_GN2))
            {
                mGlobalVar.setDeviceName("GM2");
            }
            else if(sModel==(long)Transfer_Con.HID_BOOT_MODEL_NAME_HN2)
            {
                mGlobalVar.setDeviceName("HN2");
            }
            else if(sModel==(long)Transfer_Con.HID_BOOT_MODEL_NAME_MP1)
            {
                mGlobalVar.setDeviceName("MP1");
            }
            else if(sModel==(long)Transfer_Con.HID_BOOT_MODEL_NAME_MR1)
            {
                mGlobalVar.setDeviceName("MR1");
            }
            else if(sModel==(long)Transfer_Con.HID_BOOT_MODEL_NAME_U41)
            {
                mGlobalVar.setDeviceName("U41");
            }
            else if(sModel==(long)Transfer_Con.HID_BOOT_MODEL_NAME_BX1)
            {
                mGlobalVar.setDeviceName("BX1");
            }
            else if(sModel==(long)Transfer_Con.HID_BOOT_MODEL_NAME_BX2)
            {
                mGlobalVar.setDeviceName("BX2");
            }
            else if(sModel==(long)Transfer_Con.HID_BOOT_MODEL_NAME_HN1)
            {
                mGlobalVar.setDeviceName("HN1");
            }
            else
            {
                if(sDID==0x00C05204)
                {
                    mGlobalVar.setDeviceName("HN1");
                }
                else {
                    AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                    builder.setTitle(getResources().getString(R.string.string_pop_device_update_fail))
                            .setMessage("未知的设备型号或者设备未连接！！！")
                            .create().show();
                    return;
                }
            }

            if((bootVer==sModel)||(bootVer==0)||(bootVer==0xffffffff))
            {
                Log.d(TAG,"get boote ver fail, maybe boot is old version!!");
                bootVer = (1<<24)|(1<<8);
            }


            m_ulDeviceID = sDID;
            m_CONFIG = new long[]{0xFFFFFFFF, 0xFFFFFFFF};
            ReadConfig(m_CONFIG);
            //String str = "Version: 0x" + Integer.toHexString(cVer);
            //str = str + "  DeviceID: 0x" + Long.toHexString(sDID);
            //tv_version.setText(str);
            String str = "Config: 0x" + Integer.toHexString(((int) m_CONFIG[0]) & 0xFFFFFFFD) + "  0x" + Integer.toHexString((int) m_CONFIG[1]);
            m_CONFIG_User = m_CONFIG;
            Log.d(TAG,str);
            // load code
            g_lCodeLen = LoadCode(mGlobalVar.getDeviceName());
            codeCks = 0;
            if(g_lCodeLen>0)
            {
                for(int s=0;s<g_lCodeLen;s++)
                    codeCks += (g_u8CodeBuf[s]&0xff);
            }

            Log.d(TAG,"m_CONFIG_User: 0x" + Integer.toHexString(((int) m_CONFIG_User[0])) + "  0x" + Integer.toHexString((int) m_CONFIG_User[1]));
            boolean flag = true;
            if((sModel==(long)Transfer_Con.HID_BOOT_MODEL_NAME_GM1)||(sModel==(long)Transfer_Con.HID_BOOT_MODEL_NAME_GN1))
            {
                if ((g_u8CodeBuf[0x1EEC] != 'G') || (g_u8CodeBuf[0x1EED] != 'M') || (g_u8CodeBuf[0x1EEE] != '1')) {
                    flag = false;
                }
            }
            else if((sModel==(long)Transfer_Con.HID_BOOT_MODEL_NAME_GM2)||(sModel==(long)Transfer_Con.HID_BOOT_MODEL_NAME_GN2))
            {
                if ((g_u8CodeBuf[0x1EEC] != 'G') || (g_u8CodeBuf[0x1EED] != 'M') || (g_u8CodeBuf[0x1EEE] != '2')) {
                    flag = false;
                }
            }
            else if(sModel==(long)Transfer_Con.HID_BOOT_MODEL_NAME_HN2)
            {
                if ((g_u8CodeBuf[0x1EEC] != 'H') || (g_u8CodeBuf[0x1EED] != 'N') || (g_u8CodeBuf[0x1EEE] != '2')) {
                    flag = false;
                }
            }
            else if(sModel==(long)Transfer_Con.HID_BOOT_MODEL_NAME_MP1)
            {
                if ((g_u8CodeBuf[0x0EEC] != 'M') || (g_u8CodeBuf[0x0EED] != 'P') || (g_u8CodeBuf[0x0EEE] != '1')) {
                    flag = false;
                }
            }
            else if(sModel==(long)Transfer_Con.HID_BOOT_MODEL_NAME_MR1)
            {
                if ((g_u8CodeBuf[0x0EEC] != 'M') || (g_u8CodeBuf[0x0EED] != 'R') || (g_u8CodeBuf[0x0EEE] != '1')) {
                    flag = false;
                }
            }
            else if(sModel==(long)Transfer_Con.HID_BOOT_MODEL_NAME_U41)
            {
                if ((g_u8CodeBuf[0x0EEC] != 'U') || (g_u8CodeBuf[0x0EED] != '4') || (g_u8CodeBuf[0x0EEE] != '1')) {
                    flag = false;
                }
            }
            else if(sModel==(long)Transfer_Con.HID_BOOT_MODEL_NAME_BX1)
            {
                if((g_u8CodeBuf[0x0EEC]!='B')||(g_u8CodeBuf[0x0EED]!='X')||(g_u8CodeBuf[0x0EEE]!='1'))
                {
                    flag = false;
                }
            }
            else if(sModel==(long)Transfer_Con.HID_BOOT_MODEL_NAME_BX2)
            {
                if((g_u8CodeBuf[0x0EEC]!='B')||(g_u8CodeBuf[0x0EED]!='X')||(g_u8CodeBuf[0x0EEE]!='2'))
                {
                    flag = false;
                }
            }
            else if((sModel==(long)Transfer_Con.HID_BOOT_MODEL_NAME_HN1)||(sDID==0x00C05204))
            {
                if ((g_u8CodeBuf[0x1EEC] != 'H') || (g_u8CodeBuf[0x1EED] != 'N') || (g_u8CodeBuf[0x1EEE] != '1')) {
                    flag = false;
                }
            }
            else
            {
                flag = false;
            }
            if(!flag)
            {
                AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                builder.setTitle(getResources().getString(R.string.string_pop_device_update_fail))
                        .setMessage("Boot和固件不匹配，请重新连接再尝试！！！")
                        .create().show();
                return;
            }
            m_bErase = false;
            m_bProgram_APROM = true;
            m_bProgram_NVM = false;
            m_bProgram_Config = true;
            //btn_update.setText("Disconnect");

            if (m_bProgram_APROM) {
                if (g_lCodeLen == 0) {
                    //strErr = _T("Can not load APROM file for programming!");
                    AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                    // 设置参数
                    builder.setTitle("请加载程序文档！").create().show();
                    return;
                }
            }

            if (m_bProgram_NVM) {
                if (g_lDataLen == 0) {
                    // strErr = _T("Can not load data flash file for programming!");
                    AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                    // 设置参数
                    builder.setTitle("请加载数据文档！").create().show();
                    return;
                }
            }



            new Thread() {
                public void run() {
                    int a =1;
                    try {
                        while (m_progress < 100) {

                            Thread.sleep(80);
                            if((retry<5)&&(!bIsUpdateComplete))
                            {
                                Thread_ProgramFlash();
                            }
                            if(retry==5)
                            {
                                retry++;
                                pDialog.setMessage(getResources().getString(R.string.string_pop_device_update_fail));
                                pDialog.setCanceledOnTouchOutside(true);
                                //break;
                            }
                        }
                       // pDialog.cancel();
                    } catch (InterruptedException e) {

                    }
                }
            }.start();
        }
    }

    public void viewPostion()
    {
        if(mGlobalVar.get_CurPtTbl((byte)(mGlobalVar.getDeviceMaxButton()*2),(byte)0,g_u8DataBuf))
        {
            short a;
            //String str="";
            for(a=0;a<mGlobalVar.getDeviceMaxButton();a++)
            {
                ptTbl[a] = (int)(g_u8DataBuf[2*a+1]&0xff)<<8;
                ptTbl[a] +=(int)(g_u8DataBuf[2*a]&0xff);
                //str+=String.valueOf(ptTbl[a])+", ";
            }
            //Log.d(TAG,str);
            if(mGlobalVar.get_CurPtTbl((byte)(mGlobalVar.getDeviceMaxButton()*2),(byte)1,g_u8DataBuf))
            {
                //str="";
                for(a=0;a<mGlobalVar.getDeviceMaxButton();a++)
                {
                    ptTbl[mGlobalVar.getDeviceMaxButton()+a] = (int)(g_u8DataBuf[2*a+1]&0xff)<<8;
                    ptTbl[mGlobalVar.getDeviceMaxButton()+a] += (int)(g_u8DataBuf[2*a]&0xff);
                    //str+=String.valueOf(ptTbl[mGlobalVar.getDeviceMaxButton()+a])+", ";
                }
                mGlobalVar.setPtTbl(ptTbl);
                bIsGetPtTbl = true;
                //Log.d(TAG,str);
            }
        }
        if (Settings.canDrawOverlays(MainActivity.this))
        {
            String packName = (String) dataList.get(0).get("pckname");
            for(int a=0;a<dataList.size();a++)
            {
                if((int)dataList.get(a).get("type")!=Transfer_Con.LIST_TYPE_NULL) {
                    if (((String) dataList.get(a).get("pckname")).contains(mGlobalVar.getPackageName(mGlobalVar.getmCurGame())))
                    {
                        packName = (String) dataList.get(a).get("pckname");
                        break;
                    }
                }
            }

            startLocalApp(packName);
            mGlobalVar.setFloatMode(true);
            Intent intent = new Intent(MainActivity.this,ButtonSettingService.class);
            //Toast.makeText(MainActivity.this,"已开启",Toast.LENGTH_SHORT).show();
            startService(intent);
            //finish();
        }else
        {
            //若没有权限，提示获取.
            bIs1stGetOverFloatPermit = false;
            saveUserData(false);
            Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);
            //if (Build.VERSION.SDK_INT != Build.VERSION_CODES.O)
            {
                Uri packageURI = Uri.parse("package:" + getPackageName());
                intent.setData(packageURI);
            }
            Toast.makeText(MainActivity.this,getResources().getString(R.string.string_pop_float_permitted_tip),Toast.LENGTH_SHORT).show();
            startActivity(intent);
            //startLocalApp((String)dataList.get(pos).get("pckname"));
            //finish();
        }
    }
    public boolean resolutionCompare()
    {
        float res[]={19.25f,19.5f,19,18.7f,18.5f,18,16};
        int r = mRes_Wid / 9;
        float a =  (float)mRes_Hei/r;
        //float fRatio = (float)mRes_Hei/mRes_Wid;
        Log.d(TAG,"Ratio:"+String.valueOf(a)+" : 9");
        if(!mGlobalVar.getbIsUsbConnect())
            return true;
        if(mGlobalVar.getmCurPhone()>=7)
            return true;
        return (Math.abs(res[mGlobalVar.getmCurPhone()]-a)<0.1f);
    }
    public int getResolutionIndex()
    {
        float res[]={19.25f,19.5f,19,18.7f,18.5f,18,16};
        int r = mRes_Wid / 9;
        float a =  (float)mRes_Hei/r;
        for(int k=0;k<7;k++)
        {
            if(Math.abs(res[k]-a)<0.10f)
            {
                return k;
            }
        }
        return mGlobalVar.getmCurPhone();
    }


    public boolean gameCompare(String packName,int pos,String gameName)
    {
        if(!mGlobalVar.getbIsUsbConnect())
            return true;
        if(pos>=mGlobalVar.getGameGpTotalNum())
        {
            return true;
        }

        if(mGlobalVar.getmCurGame()>=(mGlobalVar.getUserGameNum()+Transfer_Con.MAX_GP_FIX_GAME_NUM))
            return false;

        if(packName.contains("com.tencent.tmgp.pubgm"))
        {
            if(packName.contains("com.tencent.tmgp.pubgmhd"))
            {
               return (mGlobalVar.getmCurGame()==0);
            }
        }
        if(mGlobalVar.getmCurGame()==1)
        {
            return (gameName.contains(Transfer_Con.GameName[1]));
        }
        else if(mGlobalVar.getmCurGame()==2)
        {
            return (gameName.contains(Transfer_Con.GameName[2]));
        }
        return (packName.contains(mGlobalVar.getPackageName(mGlobalVar.getmCurGame())));
    }

    public int getGameIndex(String packName,String gameName)
    {
        if(packName.contains(Transfer_Con.defPackageName[1]))
        {
            if(gameName.contains(Transfer_Con.GameName[1]))
                return  1;
            else
                return 2;
        }
        for(int a=0;a<mGlobalVar.getGameGpTotalNum();a++)
        {
            if (packName.contains(mGlobalVar.getPackageName(a))) {
                return a;
            }
        }
        return mGlobalVar.getmCurGame();
    }

    public static int getVersionCode(Context context) {
        try {
            PackageManager manager = context.getPackageManager();
            PackageInfo info = manager.getPackageInfo(context.getPackageName(),
                    0);
            int versioncode = info.versionCode;
            //Log.d("SOEMain",String.valueOf(versioncode));
            return versioncode;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

    public class App_Info{
        String strVersion;
        int mVersion;
        String strDescription;
        String strUrl;
        long mAppSize;
        boolean bForceUpdate;
    }

    public void checkServerVersionCode()
    {
        app_info = new App_Info();
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder().url(VER_URL_PUSH).build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                // 下载失败监听回调
                app_info.mVersion = 0;
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String content = response.body().string();
                //Log.d(TAG,content);
                try {

                    JSONObject jsonObject = new JSONObject(content);
                    app_info.strVersion = jsonObject.getString("versionName");
                    app_info.mVersion = jsonObject.getInt("versionCode");
                    app_info.strDescription = jsonObject.getString("description");
                    app_info.strUrl = jsonObject.getString("downloadUrl");
                    Log.d(TAG,app_info.strVersion+ " code: " +String.valueOf(app_info.mVersion)+" , "+app_info.strDescription+" , "+app_info.strUrl);

                } catch (JSONException e) {
                    e.printStackTrace();
                }

                if (app_info.mVersion > getVersionCode(MainActivity.this)) {
                    //bIsAppCanUpdate = true;
                    Message msg = new Message();
                    msg.what = VERSION_CHECK_UPDATE;
                    launchHandler.sendMessage(msg);
                }
            }});
    }

    public int getServerVersionCode()
    {
        app_info = new App_Info();
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder().url(VER_URL).build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                // 下载失败监听回调
                app_info.mVersion = 0;
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String content = response.body().string();
                //Log.d(TAG,content);
                try {

                    JSONObject jsonObject = new JSONObject(content);
                    app_info.strVersion = jsonObject.getString("versionName");
                    app_info.mVersion = jsonObject.getInt("versionCode");
                    app_info.strDescription = jsonObject.getString("description");
                    app_info.strUrl = jsonObject.getString("downloadUrl");
                    Log.d(TAG,app_info.strVersion+ " code: " +String.valueOf(app_info.mVersion)+" , "+app_info.strDescription+" , "+app_info.strUrl);
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                if (app_info.mVersion > getVersionCode(MainActivity.this)) {
                    //bIsAppCanUpdate = true;
                    Message msg = new Message();
                    msg.what = VERSION_CHECK_UPDATE;
                    launchHandler.sendMessage(msg);
                }
                else
                {
                    Message msg = new Message();
                    msg.what = VERSION_CHECK_NOUPDATE;
                    launchHandler.sendMessage(msg);
                }
            }});
        return app_info.mVersion;
    }

    public static String getVersionName(Context context) {
        try {
            PackageManager manager = context.getPackageManager();
            PackageInfo info = manager.getPackageInfo(context.getPackageName(),
                    0);
            String version = info.versionName;
            return version;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "0";
    }

    public void downFile(String url, String fileName) {
        pDialog = new ProgressDialog(MainActivity.this);
        pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        pDialog.setTitle(getResources().getString(R.string.string_pop_app_update_download));
        pDialog.setMessage(getResources().getString(R.string.string_pop_app_update_wait));
        pDialog.setProgress(0);
        pDialog.setMax(100);
        pDialog.show();
        pDialog.setCancelable(false);

        DownloadUtils downloadUtils = new DownloadUtils();
        downloadUtils.get().download(url, Environment.getExternalStorageDirectory().getAbsolutePath()+LOCAL_PATH,
                fileName +".apk", new DownloadUtils.OnDownloadListener() {
                    @Override
                    public void onDownloadSuccess(File file) {
                        if (pDialog != null && pDialog.isShowing()) {
                            pDialog.dismiss();
                        }
                        //下载完成进行相关逻辑操作
                        update();
                    }

                    @Override
                    public void onDownloading(int progress,long total) {
                        pDialog.setProgress(progress);
                        mGlobalVar.mAppSize = total;
                    }

                    @Override
                    public void onDownloadFailed(Exception e) {
                        //下载异常进行相关提示操作
                        pDialog.dismiss();
                        //Toast.makeText(MainActivity.this,e.toString(),Toast.LENGTH_SHORT).show();
                        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                        builder.setTitle(getResources().getString(R.string.string_pop_app_update_download_fail))
                                .setMessage(e.toString())
                                .setPositiveButton(getResources().getString(R.string.string_pop_confirm), new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+LOCAL_PATH+NAME_UPDATE_APK);
                                        if(file.exists())
                                        {
                                            file.delete();
                                        }
                                    }
                                }).create().show();
                    }
                });
    }
    private void update() {
        //安装应用
        Intent intent = new Intent(Intent.ACTION_VIEW);

        if(Build.VERSION.SDK_INT>= Build.VERSION_CODES.N) {

            Uri contentUri = FileProvider.getUriForFile(this,"com.opd.soeghtool.fileProvider",new File(Environment
                    .getExternalStorageDirectory(), LOCAL_PATH+NAME_UPDATE_APK));

            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

            intent.setDataAndType(contentUri,"application/vnd.android.package-archive");

        }else{

            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setDataAndType(Uri.fromFile(new File(Environment
                            .getExternalStorageDirectory(), LOCAL_PATH+NAME_UPDATE_APK)),
                    "application/vnd.android.package-archive");
        }
        startActivity(intent);
    }

    public void saveUserData(boolean write_now)
    {
        SharedPreferences.Editor editor = getSharedPreferences(Transfer_Con.SAVENAME, MODE_PRIVATE).edit();
        editor.putBoolean("DataExist",true);
        editor.putString("userID","User00000001");
        editor.putString("userName","手易用户");
        int totalGame = mGlobalVar.getGameGpTotalNum();
        editor.putInt("totalGame", totalGame);
        editor.putInt("listTotalGame", mGlobalVar.getGameListTotalNum());
        editor.putInt("userGameNum", mGlobalVar.getUserGameNum());

        editor.putInt("totalGameKb", mGlobalVar.getGameGpTotalNumKB());
        editor.putInt("listTotalGameKb", mGlobalVar.getGameListTotalNumKB());
        editor.putInt("userGameNumKb", mGlobalVar.getUserGameNumKB());
        editor.putInt("ImgSize", mGlobalVar.getPt_Tbl_View_Size());
        editor.putInt("ImgAlpha", mGlobalVar.getPt_Tbl_View_Alpha());
        editor.putInt("LogoSize", mGlobalVar.getFloat_Icon_Size());
        editor.putInt("ImgNorSize", mGlobalVar.getNormal_Icon_Size());
        editor.putInt("ImgNorAlpha", mGlobalVar.getNormal_Icon_Alpha());
        editor.putBoolean("FirstGetPerm", bIs1stGetOverFloatPermit);
        editor.putBoolean("GameGuide", mGlobalVar.getIsEnterGameNeedGuide());
        editor.putBoolean("AdvSetGuide", mGlobalVar.getIsAdvSetNeedGuide());
        editor.putBoolean("InjectFirst",bInjectFirstTime);
        editor.putBoolean("InjectVerify", bInjectVerifyFail);
        editor.putBoolean("ReadIntroduce", bIsAlreadyReadIntroduce);
        editor.putBoolean("InjectMode", mGlobalVar.getIsInjectData());
        editor.putInt("Language", mGlobalVar.getCurLanguageIndex());
        editor.putInt("lastCntDevIdx", mGlobalVar.getLastConnectDeviceIndex());
        editor.putBoolean("cntBefore", bIsConnectedBefore);
        editor.putBoolean("AutoSwHDMI", mGlobalVar.getIsAutoSwitchToHDMI());
        editor.putBoolean("ManualHDMI", mGlobalVar.getIsManualSetToHDMI());
        editor.putBoolean("ForceView", mGlobalVar.getIsForceViewOut());
        editor.putBoolean("VirtualMouse", mGlobalVar.getIsUseVirtualMouse());
        editor.putInt("MouseInterval", mGlobalVar.getVirtualMouseInterval());
        editor.putInt("HDMIWidth", mGlobalVar.getManualHDMIWidth());
        editor.putInt("HDMIHeight", mGlobalVar.getManualHDMIHeight());
        editor.putInt("RockerRange_KB", mGlobalVar.getRockerMoveRange_KB());
        editor.putBoolean("AudioOut", mGlobalVar.getIsAudioOut());
        editor.putBoolean("IsSetMouse", bIsSendMouseSwitchToDevice);
        //editor.putInt("defGameExistNum", mGlobalVar.getGameDefExist());
        for(int a=0;a<totalGame;a++)
        {
            editor.putString("PackageName"+String.valueOf(a),mGlobalVar.getPackageName(a));
            //Log.d(TAG,"a="+String.valueOf(a)+"  "+mGlobalVar.getPackageName(a));
        }
        for(int a=0;a<mGlobalVar.getUserGameNum();a++)
        {   // game name
            editor.putString("usrGameName"+String.valueOf(a),mGlobalVar.getUserGameName(a));
        }
        for(int a=0;a<mGlobalVar.getGameGpTotalNumKB();a++)
        {
            editor.putString("PackageNameKb"+String.valueOf(a),mGlobalVar.getPackageNameKB(a));
            //Log.d(TAG,"a="+String.valueOf(a)+"  "+mGlobalVar.getPackageName(a));
        }
        for(int a=0;a<mGlobalVar.getUserGameNumKB();a++)
        {   // game name
            editor.putString("usrGameNameKb"+String.valueOf(a),mGlobalVar.getUserGameNameKB(a));
        }
        if(write_now)
            editor.commit();
        else
            editor.apply();
    }

    public boolean isExternalStorageWritable() {
        String state = Environment.getExternalStorageState();
        if (Environment.MEDIA_MOUNTED.equals(state)) {
            return true;
        }
        return false;
    }



    public void loadUserData()
    {
        SharedPreferences read = getSharedPreferences(Transfer_Con.SAVENAME, MODE_PRIVATE);
        if(read==null)
        {
            read = getSharedPreferences(Transfer_Con.SAVENAME, MODE_PRIVATE);
        }
        mGlobalVar.setIsWaitForUPdate(read.getBoolean("waitUpdate",false));
        if(read.getBoolean("DataExist",false)) {
            int totalGame =0 ;
            mGlobalVar.setLastConnectDeviceIndex(read.getInt("lastCntDevIdx", 0));
            bIsConnectedBefore = (read.getBoolean("cntBefore", false));
            //Log.d(TAG, "totalGame:" + String.valueOf(totalGame));

            mGlobalVar.setPt_Tbl_View_Size(read.getInt("ImgSize", 5));
            mGlobalVar.setPt_Tbl_View_Alpha(read.getInt("ImgAlpha", 5));
            mGlobalVar.setFloat_Icon_Size(read.getInt("LogoSize", 5));
            mGlobalVar.setNormal_Icon_Size(read.getInt("ImgNorSize", 5));
            mGlobalVar.setNormal_Icon_Alpha(read.getInt("ImgNorAlpha", 5));
            bIs1stGetOverFloatPermit = read.getBoolean("FirstGetPerm", true);

            mGlobalVar.setIsEnterGameNeedGuide( read.getBoolean("GameGuide", true));
            mGlobalVar.setIsFloatMenuGuide( read.getBoolean("FloatMenu", true));
            mGlobalVar.setIsAdvSetNeedGuide( read.getBoolean("AdvSetGuide", true));


            mGlobalVar.setIsInjectMode( read.getBoolean("InjectMode", true));
            bInjectFirstTime =read.getBoolean("InjectFirst", true);
            bInjectVerifyFail =read.getBoolean("InjectVerify", false);
            bIsAlreadyReadIntroduce =read.getBoolean("ReadIntroduce", false);
            mGlobalVar.setCurLanguageIndex(read.getInt("Language", 0));
            //Log.d(TAG, "userGameNum:" + String.valueOf(mGlobalVar.getUserGameNum()));
            //mGlobalVar.setGameDefExist(read.getInt("defGameExistNum", 0));
            //Log.d(TAG, "defGameExistNum:" + String.valueOf(mGlobalVar.getGameDefExist()));
            mGlobalVar.setGameGpTotalNumKB(read.getInt("totalGameKb", 0));
            mGlobalVar.setGameListTotalNumKB(read.getInt("listTotalGameKb", 0));
            mGlobalVar.setUserGameNumKB(read.getInt("userGameNumKb", 0));
            mGlobalVar.setIsAutoSwitchToHDMI(read.getBoolean("AutoSwHDMI", true));
            mGlobalVar.setIsManualSetToHDMI(read.getBoolean("ManualHDMI", false));
            mGlobalVar.setIsForceViewOut(read.getBoolean("ForceView", false));
            mGlobalVar.setIsUseVirtualMouse(read.getBoolean("VirtualMouse", true));
            mGlobalVar.setVirtualMouseInterval(read.getInt("MouseInterval", 20));
            mGlobalVar.setManualSetHDMIWidth(read.getInt("HDMIWidth", 1920));
            mGlobalVar.setManualSetHDMIHeight(read.getInt("HDMIHeight", 1080));
            mGlobalVar.setRockerMoveRange_KB(read.getInt("RockerRange_KB", 100));
            mGlobalVar.setIsAudioOut(read.getBoolean("AudioOut", false));
            bIsSendMouseSwitchToDevice = read.getBoolean("IsSetMouse", false);

            if(mGlobalVar.getGameGpTotalNumKB()>(mGlobalVar.getUserGameNumKB()+Transfer_Con.MAX_GP_FIX_GAME_NUM_KB))
            {
                totalGame = (mGlobalVar.getUserGameNumKB()+Transfer_Con.MAX_GP_FIX_GAME_NUM_KB);
                mGlobalVar.setGameGpTotalNumKB(totalGame);
            }

            mGlobalVar.setGameGpTotalNum(read.getInt("totalGame", 0));
            mGlobalVar.setGameListTotalNum(read.getInt("listTotalGame", 0));
            mGlobalVar.setUserGameNum(read.getInt("userGameNum", 0));
            if(mGlobalVar.getGameGpTotalNum()>(mGlobalVar.getUserGameNum()+Transfer_Con.MAX_GP_FIX_GAME_NUM))
            {
                totalGame = (mGlobalVar.getUserGameNum()+Transfer_Con.MAX_GP_FIX_GAME_NUM);
                mGlobalVar.setGameGpTotalNum(totalGame);
            }


                for (int a = 0; a < mGlobalVar.getGameGpTotalNumKB(); a++) {   // Package
                    mGlobalVar.setPackageNameKB(a, read.getString("PackageNameKb" + String.valueOf(a), null));
                    Log.d(TAG, "packagenameKB:" + mGlobalVar.getPackageNameKB(a));
                }

            if((mGlobalVar.getGameGpTotalNumKB()==0))
            {
                mGlobalVar.setGameGpTotalNumKB(1);
                mGlobalVar.setPackageNameKB(0, Transfer_Con.initPackageName[0]);
            }

                for(int a=0;a<mGlobalVar.getUserGameNumKB();a++)
                {   // Label
                    mGlobalVar.setUserGameNameKB(a,read.getString("usrGameNameKb" + String.valueOf(a),""));
                }

                for (int a = 0; a < mGlobalVar.getGameGpTotalNum(); a++) {   // Package
                    mGlobalVar.setPackageName(a, read.getString("PackageName" + String.valueOf(a), null));
                    Log.d(TAG, "packagename:" + mGlobalVar.getPackageName(a));
                }
                for(int a=0;a<mGlobalVar.getUserGameNum();a++)
                {   // Label
                    mGlobalVar.setUserGameName(a,read.getString("usrGameName"+String.valueOf(a),""));
                }

            if(!bIsConnectedBefore)
            {
                if(mGlobalVar.getIsEnterGameNeedGuide()||mGlobalVar.getIsFloatMenuGuide()||mGlobalVar.getIsAdvSetNeedGuide()||(mGlobalVar.getUserGameNum()!=0))
                {
                    bIsConnectedBefore = true;
                    mGlobalVar.setLastConnectDeviceIndex(Transfer_Con.DEVICE_HN1_INDEX);
                }
            }

            try {
                JSONArray jsonArray = new JSONArray(read.getString("ptExist", "[]"));
                for (int i = 0; i < jsonArray.length(); i++) {
                    byte temp = (byte)jsonArray.getInt(i);
                    for(int a =0;a<8;a++)
                    {
                       mGlobalVar.setIsPtExit(i,a,(temp&(1<<a))==(1<<a));
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        else
        {
            bInjectFirstTime = true;
            bInjectVerifyFail =  false;
            bIsAlreadyReadIntroduce = false;
            bIsConnectedBefore = false;

            {
                mGlobalVar.setGameGpTotalNum(Transfer_Con.MAX_GP_FIX_GAME_NUM);
                for (int a = 0; a < Transfer_Con.MAX_GP_FIX_GAME_NUM; a++) {
                    mGlobalVar.setPackageName(a, Transfer_Con.defPackageName[a]);
                }
                mGlobalVar.setGameGpTotalNumKB(1);
                mGlobalVar.setPackageNameKB(0, Transfer_Con.initPackageName[0]);
            }
            saveUserData(false);
        }
    }

    public void refreshGameList()
    {
        dataList = new ArrayList<Map<String, Object>>();
        final PackageManager packageManager = MainActivity.this.getPackageManager();
        List<PackageInfo> packageInfoList = packageManager.getInstalledPackages(PackageManager.MATCH_UNINSTALLED_PACKAGES);
        if (packageInfoList != null) {
            int gameCouter = 0;
            int defGameNum = 0;
            //Log.d(TAG,"---------------------------->123");
            if(mGlobalVar.getIsCurDeviceGamePad())
            {
                for (int s = 0; s < (Transfer_Con.MAX_GP_FIX_GAME_NUM + mGlobalVar.getUserGameNum()); s++) {
                    for (int i = 0; i < packageInfoList.size(); i++) {
                        if ((packageInfoList.get(i).applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
                            continue;
                        }
                        String packName = packageInfoList.get(i).packageName;
                        if (packName.contains(s>=Transfer_Con.MAX_GP_FIX_GAME_NUM?mGlobalVar.getPackageName(s):Transfer_Con.defPackageName[s])) {
                            Map<String, Object> map = new HashMap<String, Object>();
                            map.put("id", String.valueOf(gameCouter + 1));
                            map.put("icn", packageInfoList.get(i).applicationInfo.loadIcon(getPackageManager()));
                            if (s == 1)
                                map.put("name", packageInfoList.get(i).applicationInfo.loadLabel(getPackageManager()) + "3" + getResources().getString(R.string.string_pop_game_list_skill));
                            else if (s == 2)
                                map.put("name", packageInfoList.get(i).applicationInfo.loadLabel(getPackageManager()) + "4" + getResources().getString(R.string.string_pop_game_list_skill));
                            else
                                map.put("name", packageInfoList.get(i).applicationInfo.loadLabel(getPackageManager()));
                            //map.put("name", (String) packageInfoList.get(i).packageName);
                            //Log.d(TAG,(String) packageInfoList.get(i).packageName);
                            map.put("pckname", (String) packageInfoList.get(i).packageName);
                            map.put("add", R.drawable.plus);
                            map.put("rev", R.drawable.minus);
                            map.put("start", getResources().getString(R.string.string_pop_game_list_enter));
                            if (s < Transfer_Con.MAX_GP_FIX_GAME_NUM) {
                                defGameNum++;
                                map.put("type", Transfer_Con.LIST_TYPE_DEF);
                            } else {
                                map.put("type", Transfer_Con.LIST_TYPE_USER);
                            }
                            dataList.add(map);
                            gameCouter++;
                            break;
                        }
                    }
                }
                mGlobalVar.setGameDefExist(defGameNum);
                mGlobalVar.setGameListTotalNum(gameCouter);
            }
            else //if((mGlobalVar.getDeviceIndex()==Transfer_Con.DEVICE_MP1_INDEX)||(mGlobalVar.getDeviceIndex()==Transfer_Con.DEVICE_BX1_INDEX)||(mGlobalVar.getDeviceIndex()==Transfer_Con.DEVICE_BX2_INDEX))
            {
                for (int s = 0; s < (Transfer_Con.MAX_GP_FIX_GAME_NUM_KB + mGlobalVar.getUserGameNumKB()); s++) {
                    for (int i = 0; i < packageInfoList.size(); i++) {
                        if ((packageInfoList.get(i).applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
                            continue;
                        }

                        String packName = packageInfoList.get(i).packageName;

                        if (packName.contains(s>=Transfer_Con.MAX_GP_FIX_GAME_NUM_KB?mGlobalVar.getPackageNameKB(s):Transfer_Con.initPackageName[s])) {
                            Map<String, Object> map = new HashMap<String, Object>();
                            map.put("id", String.valueOf(gameCouter + 1));
                            map.put("icn", packageInfoList.get(i).applicationInfo.loadIcon(getPackageManager()));
                            map.put("name", packageInfoList.get(i).applicationInfo.loadLabel(getPackageManager()));
                            //map.put("name", (String) packageInfoList.get(i).packageName);
                            //Log.d(TAG,(String) packageInfoList.get(i).packageName);
                            map.put("pckname", (String) packageInfoList.get(i).packageName);
                            map.put("add", R.drawable.plus);
                            map.put("rev", R.drawable.minus);
                            map.put("start", getResources().getString(R.string.string_pop_game_list_enter));
                            if (s < Transfer_Con.MAX_GP_FIX_GAME_NUM_KB) {
                                defGameNum++;
                                map.put("type", Transfer_Con.LIST_TYPE_DEF);
                            } else {
                                map.put("type", Transfer_Con.LIST_TYPE_USER);
                            }
                            dataList.add(map);
                            gameCouter++;
                            break;
                        }
                    }
                }
                mGlobalVar.setGameDefExistKB(defGameNum);
                mGlobalVar.setGameListTotalNumKB(gameCouter);
            }
            if(Transfer_Con.ENABLE_GAME_DATA_IN_PHONE_GP)
            {
                if (dataList.size() < Transfer_Con.MAX_GAME_NUM_IN_PHONE)
                {
                    Map<String, Object> map = new HashMap<String, Object>();
                    map.put("id", String.valueOf(dataList.size() + 1));
                    //map.put("name", (String) packageInfoList.get(i).packageName);
                    //map.put("pckname", (String) packageInfoList.get(a).packageName);
                    map.put("add", R.drawable.plus);
                    map.put("rev", R.drawable.minus);
                    map.put("type", Transfer_Con.LIST_TYPE_NULL);
                    //map.put("start", "Start");
                    dataList.add(map);
                }
            }
            else {
                if (dataList.size() < Transfer_Con.MAX_GAME_NUM) {
                    for (int a = dataList.size(); a < Transfer_Con.MAX_GAME_NUM; a++) {
                        Map<String, Object> map = new HashMap<String, Object>();
                        map.put("id", String.valueOf(a + 1));
                        //map.put("name", (String) packageInfoList.get(i).packageName);
                        //map.put("pckname", (String) packageInfoList.get(a).packageName);
                        map.put("add", R.drawable.plus);
                        map.put("rev", R.drawable.minus);
                        map.put("type", Transfer_Con.LIST_TYPE_NULL);
                        //map.put("start", "Start");
                        dataList.add(map);
                    }
                }
            }
            myAdapter = new MyAdapter(this);
            lv_gamelist.setAdapter(myAdapter);
        }
    saveUserData(false);
    }

    @Override
    public void onResume() {
        super.onResume();
        refreshGameList();
        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getRealMetrics(dm);
        //Log.d(TAG,String.format("w=%d,h=%d,w1=%d,h1=%d,w1=%d,h1=%d,",dm.heightPixels,dm.widthPixels,mRes_Hei,mRes_Wid,mGlobalVar.getScreenWidth(),mGlobalVar.getScreenHeight()));
        if((dm.heightPixels!=mRes_Hei)||(dm.widthPixels!=mRes_Wid))
        {
            if (dm.heightPixels > dm.widthPixels) {
                mRes_Wid = dm.widthPixels;
                mRes_Hei = dm.heightPixels;
            } else {
                mRes_Hei = dm.widthPixels;
                mRes_Wid = dm.heightPixels;
            }
            mGlobalVar.setScreenWidth(mRes_Wid);
            mGlobalVar.setScreenHeight(mRes_Hei);
            if(mGlobalVar.getbIsUsbConnect())
            {
                if(mGlobalVar.getIsCurDeviceKB()) {
                    Intent intent2 = new Intent(MainActivity.this, FloatMenuService_New.class);
                    stopService(intent2);
                    //Log.d(TAG,"FloatMenuService_New stop");
                }
                else
                {
                    Intent intent = new Intent(MainActivity.this, FloatMenuService.class);
                    stopService(intent);
                    //Log.d(TAG,"FloatMenuService stop");
                }
            }
        }

        if(!mGlobalVar.getbIsUsbConnect())
        {
            if(mGlobalVar.myUsbDevice==null) {
                mGlobalVar.enumDevice();
            }
            if(mGlobalVar.myUsbDevice!=null)
            {
                //插入的时候系统会自行进行申请 需要知道系统的广播
                if(!mGlobalVar.myUsbManager.hasPermission(mGlobalVar.myUsbDevice)) {
                    //requestUSBPermit();
                    //Message msg = new Message();
                    //msg.what = USBPermitRequest;//LAUNCHSCREEN;
                    //launchHandler.sendMessageDelayed(msg, 10000);
                    handler.postDelayed(runnable, 1000);
                }
                else if(mGlobalVar.connectDevice())
                {
                    //Log.d(TAG,"connectDevice ");
                    if(mGlobalVar.getbIsTransferMode()) {

                        getAllDataAndShow();
                    }
                    //launchLayout.setVisibility(View.GONE);
                    iv_top_connect.setImageResource(R.drawable.connect);
                    tv_connect_mode_cnt_sta.setText(mGlobalVar.getDeviceName()+getResources().getString(R.string.string_pop_connect_already_connect));
                    iv_connect_mode_cnt_sta.setImageResource(R.drawable.connect);
                    tv_device_update_version_cur.setText(mGlobalVar.getStrFwVer());
                    if(mGlobalVar.getDeviceIndex()==Transfer_Con.DEVICE_GM1_INDEX)
                    {
                        if (mGlobalVar.tranGet_Value(Transfer_Con.HID_CMD_GET_HW_SETTING, 0, 0x84, g_u8DataBuf)) {
                            if ((g_u8DataBuf[0] & 0x80) == 0x80) {
                                if((g_u8DataBuf[0] & 0x04) == 0x04) {
                                    mGlobalVar.setIsPC360Mode(true);
                                    mGlobalVar.setIsSimulateMode(true);
                                }
                                else {
                                    mGlobalVar.setIsSimulateMode(true);
                                    mGlobalVar.setIsPC360Mode(false);
                                }
                            } else {
                                mGlobalVar.setIsSimulateMode(false);
                                mGlobalVar.setIsPC360Mode(false);
                            }
                        }
                    }
                    else {
                        if (mGlobalVar.tranGet_Value(Transfer_Con.HID_CMD_GET_HW_SETTING, 0, mGlobalVar.getIsSupportMenuKey() ? 0x80 : 0, g_u8DataBuf)) {
                            if ((g_u8DataBuf[0] & 0x80) == 0x80) {
                                mGlobalVar.setIsSimulateMode(true);
                            } else {
                                mGlobalVar.setIsSimulateMode(false);
                            }
                        }
                    }
                    if(mGlobalVar.getIsCurDeviceGamePad())
                        sendSimulateMode();
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    if(mGlobalVar.getbIsTransferMode())
                        sendConnectStatus(true,true);
                }
            }
        }
    }
}
